1

I have this code:

var Class = function(){ // function constructor
this.className = 'Class';
}
Class.prototype.method = function(){ // open method
alert('method of ' + this.className);
}

var ClassSub = function(){ // function constructor of sub class
this.className = 'ClassSub';
}
ClassSub.prototype = new Class(); 

var objSub = new ClassSub(); 
objSub.method(); 

And I have one qustion: Class.prototype.method = function(){ // open method

when we write like that we say that that prototype of our class will have this method. So his subclasses will have this method to. But what i can't understand is why we can't just write

Class.method = function()
user2114177
  • 263
  • 1
  • 9
  • 17
  • 1
    That syntax treats Class as an ordinary function object, not as a constructor of Class object instances. –  Oct 27 '13 at 19:58
  • @Jeffman - please speak clear. what are you pointing to (referring to)? – ncm Oct 27 '13 at 20:01
  • what is you question? are you saying what is the reason of using `classname.prototype.methodname` and why we are not using `classname.methodname`? – ncm Oct 27 '13 at 20:06

2 Answers2

1

Class.method = function () {};

That would just add a method property on the constructor function Class. Functions are objects and can hold data just like any other objects. However, the reason that will not add the method function to Class instances is simple: that's not how prototypal inheritance is implemented in JavaScript.

You should read about What is the 'new' keyword in JavaScript? and you will understand how the prototype chain is being setup and why adding members to a constructor function will not influence instances created using this constructor.

I think it's also worth mentionning that ClassSub.prototype = new Class(); is not an efficient way of setting up the prototype chain since it will run the Class constructor's code.

In modern browsers you can simply use Object.create and there are shim for old browsers.

ClassSub.prototype = Object.create(Class.prototype);

Community
  • 1
  • 1
plalx
  • 39,329
  • 5
  • 63
  • 83
0

As mentioned in the comments, Class.method creates a property for the variable Class. not the instances of Class.

var Class = function () { /* some code */ }
Class.method = function () { }
console.log(Class.method); // function () { }
console.log(new Class().method); // undefined

Class.prototype.method = function () { }
console.log(new Class().method); // function () { }
Artyom Neustroev
  • 8,224
  • 4
  • 29
  • 54