开发者

What does "the prototype belongs to the class not the instance" mean in javascript?

I asked the question:

Why cant I declare a constructor instantiate an object and then access the prototype?

And you can see that I have marked the answer. I understand the response but Im a bit confused as to what he means by:

The prototype belongs to the class, not the instance:

Does this mean that javascript has a class in this example? I thought javascript was classless? It only has function constructors... At what point does a function constructor become a cl开发者_C百科ass? Is it when you add other members to it using the .prototype accessor?


Actually class is an OOP term, not really javascript. What is meant is that the prototype belongs to the constructor. So in

function MyConstructor(prop){
   this.foo = prop || 'foo';
}
MyConstructor.prototype.bar = 'allways bar';
var mc1 = new MyConstructor('I am mc1'), 
    mc2 = new MyConstructor('I am mc2');

alert(mc1.bar) ; //=> allways bar
alert(mc2.bar) ; //=> allways bar
alert(mc1.foo) ; //=> I am mc1
alert(mc2.foo) ; //=> I am mc2

bar belongs to the constructors (MyConstructor) prototype. It will always be 'allways bar', for every instance. foo is an instance property (with a default value 'foo') and can be assigned with a different value for every instance.


Ya prototype of JavaScript is a concept quite similar to class but not exactly the same. Read the article below, it offers one of the best explanations available on internet on this issue.

http://www.crockford.com/javascript/inheritance.html


There are no classes in javascript.

Constructors are functions and have a prototype property that references an object. You can add functions to that object, or assign a new object to the prototype property to create an inheritance chain:

function MyConstructor () {
  // initialise instance
}

MyConstructor.prototype.someMethod = function() {
    // ...
  };

MyConstructor.prototype.anotherMethod = function() {
    // ...
};

or replace it with an instance of another constructor:

MyConstructor.prototype = new SomeOtherConstructor();

MyConstructor.prototype.constructor = MyConstructor;

and so on. Now when an instance of MyConstructor is created:

var anInstance = new MyConstructor();

The object returned by the constructor has MyConstructor.prototype as its internal [[prototype]] property and "inherits" its methods and properties (and those on its entire [[prototype]] chain).

So each instance of MyConstructor has its MyConstructor.prototype on its prototype chain. Note however that MyConstructor doesn't inherit from it's own prototype, it is only used by instances created by new MyConstructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜