gpt4 book ai didi

Javascript 原型(prototype)继承

转载 作者:行者123 更新时间:2023-11-29 19:43:00 26 4
gpt4 key购买 nike

我正在阅读 Alex Maccaw 的 Javascript Web Applications。下面是构建类构造函数的片段。

    var Class = function(parent){
var klass = function(){
this.init.apply(this, arguments);
};

// Change klass' prototype
if (parent) {
var subclass = function() { };
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
};

klass.prototype.init = function(){};

// Shortcuts
klass.fn = klass.prototype;
klass.fn.parent = klass;
klass._super = klass.__proto__;

/* include/extend code... */

return klass;
};

我感兴趣的是

    var subclass = function() { };
subclass.prototype = parent.prototype;
klass.prototype = new subclass;

他为什么不去

    klass.prototype = parent.prototype;

他解释说:“这种围绕创建临时匿名函数的小舞蹈可以防止在继承类时创建实例”。这对我来说仍然没有意义,怎么会

    klass.prototype = parent.prototype;

创建实例?

最佳答案

因为你放在klass.prototype 上的任何东西也会在parent.prototype 上运行,因为它们是同一个对象。

他正在做的是创建一个继承parent.prototype 的新对象,并将该对象分配给 klass.prototype,这样添加到它的任何属性,不要放在 parent.prototype 上。


仅供引用,一种更现代的方法是使用 Object.create()

klass.prototype = Object.create(parent.prototype);

这基本上完成了同样的事情。


你指出的这句话:

" "This little dance around creating a temporary anonymous function prevents instances from being created when a class is inherited""

...是一种奇怪的解释方式,除非有更有意义的上下文。也许他的意思是说您不需要调用 parent 构造函数来获取从 parent.prototype 继承的对象。

如果你这样做:

klass.prototype = new parent();

它会完成同样的事情,除了 parent 构造函数会被调用,这样做可能会产生不希望的副作用。

关于Javascript 原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21865820/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com