开发者

javascript constructor reset: What is it?

I came across this slide: http://www.slideshare.net/stoyan/javascript-patterns#postComment

at page 35:

Option 5 + super + constructor reset

function inherit(C, P) {
    var F = function(){};
    F.prototype = P.开发者_开发知识库prototype;
    C.prototype = new F();
    C.uber = P.prototype;
    C.prototype.constructor = C;  // WHY ???
}

I don't get it. Can anybody please explain what the last line for ?

    C.prototype.constructor = C;  // WHY ???

Thanks


This gives an explanation http://phrogz.net/JS/Classes/OOPinJS2.html

In particular

Cat.prototype = new Mammal();        // Here's where the inheritance occurs 
Cat.prototype.constructor=Cat;       // Otherwise instances of Cat would have a constructor of Mammal 


Note: I believe this reset isn't needed anymore if using #2 of the options below:

I believe you can either use these options for doing inheritance:

*1. do via Object.create (i do see this syntax more often nowadays):

Cat.prototype = Object.create(Mammal.prototype);//before this line of code has ran (where you can assume the Cat function is defined), the Cat.prototype was empty with a .prototype that correctly pointed to Cat... now it got overridden with Mammal's prototype inherited here which points to Mammal's constructor... need to reset on next line
Cat.prototype.constructor = Cat; //Since when prototype copied its constructor needs to get re-set/changed to the child constructor

*2. via setPrototypeOf

Object.setPrototypeOf(Cat.prototype, Mammal.prototype); 
//don't need to reset Cat.prototype.constructor in this case; 'seems smarter'

*3. via new; Don't think this way recommended anymore (although this was the way I originally learned how to set the inheritance many years ago). I believe I read setting the prototype this way via 'new ParentClass()' isn't recommended anymore as it will copy properties that aren't needed in the proto object I believe (properties you usually would set in an instance with a super(constructorParams) or ParentClass.call(this, constructorParams) in Cat's constructor/function so they should they be shared across all instances via the prototype).

Cat.prototype = new Mammal();
Cat.prototype.constructor=Cat;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜