javascript构造函数重置:它是什么?

时间:2010-04-11 10:18:56

标签: javascript oop

我看到了这张幻灯片:http://www.slideshare.net/stoyan/javascript-patterns#postComment

,第35页:

选项5 +超级+构造函数重置

function inherit(C, P) {
    var F = function(){};
    F.prototype = P.prototype;
    C.prototype = new F();
    C.uber = P.prototype;
    C.prototype.constructor = C;  // WHY ???
}

我不明白。任何人都可以解释最后一行是什么?

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

由于

2 个答案:

答案 0 :(得分:11)

这给出了解释http://phrogz.net/JS/Classes/OOPinJS2.html

特别是

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

答案 1 :(得分:0)

注意:我相信如果使用以下选项中的#2,就不再需要此重置:

我相信您可以使用以下选项进行继承:

* 1。通过Object.create进行操作(我现在经常看到这种语法):

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。通过setPrototypeOf

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

* 3。通过新;不要认为这种方式推荐了(尽管这是我多年前最初学习如何设置继承的方式)。 我相信我不建议再通过这种方式通过'new ParentClass()设置原型,因为它会复制我相信的原型对象不需要的属性(您通常会在具有super( Cat的构造函数/函数中的ConstructorParams)或ParentClass.call(this,constructorParams),因此应该通过原型在所有实例之间共享它们。

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