4

I am learning OOP Javascript and I wonder why i need to use the constructor.prototype functionality. Can't I just put all the functionality i need in the construtor function like so:

function Class(){
    this.x = x;
    this.y = y;
    this.--- = ---;
}

rather than:

function Class(){
    this.x = x;
}

Class.prototype = {
    constructor : Class,
    y : y
}
3
  • If you want to help yourself with OOP in JavaScript forget the word 'class' exists for a while, and go read: Working with objects Commented Jun 17, 2015 at 13:55
  • @Oka I disagree, it's very common to use prototypal inheritance to emulate classes. That's why EcmaScript6 has a class keyword. Yes, you should understand what prototypal inheritance means. See js-bits.blogspot.com/2014/10/… Commented Jun 17, 2015 at 14:00
  • They're still not classes, though. The keyword is syntactic sugar - it doesn't magically change the language from a prototypical language to a classical one. Commented Jun 17, 2015 at 14:22

1 Answer 1

6

Defining your methods/properties in the prototype will allow them to be shared between instances. Defining them in the constructor creates a new one for each instance.

You don't have to use the prototype... Use it if you want to share data. Typically you put methods on the prototype (because they don't change) and you set values on the instance itself.


One thing to beware, that often causes bugs, is defining mutable properties on the prototype. I've posted about this in Understanding prototypal inheritance

function Class(){}   
Class.prototype = { obj : {}};

var a = new Class();
a.obj.x = 5;

var b = new Class();
console.log(b.obj.x); // 5

So you typically should define objects in the constructor (if you don't want them shared);

 function Class(){ 
     this.obj = {};
 }   

var a = new Class();
a.obj.x = 5;

var b = new Class();
console.log(b.obj.x); // undefined

Note that this is not a problem for primitives, because they can't be mutated, setting them on an instance just shadows the value from the prototype.

function Class(){}   
Class.prototype = { val : 5};

var a = new Class();
console.log(a.val); // 5
a.val = 6;
console.log(a.val); // 6

var b = new Class();
console.log(b.val); // 5
Sign up to request clarification or add additional context in comments.

2 Comments

Assigning to an object property always assigns to an own property, it never assigns to the [[Prototype]] property. The type of value assigned is irrelevant.
@RobG That's why I explained that it shadows the property from the prototype, the relevant part is that for primitives, you have to assign a new value (on the object itself), you can't mutate it as you can objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.