gpt4 book ai didi

JavaScript 模式 : "copy" ClassA properties to ClassB

转载 作者:行者123 更新时间:2023-11-30 10:34:32 27 4
gpt4 key购买 nike

在一些大型项目中看到这种 JavaScript 模式,它将 ClassA 的属性“复制”或“实现”到 ClassB,但无法弄清楚使用“.call()”在 ClassB 的构造函数中调用 ClassA 的空构造函数的目的是什么将 ClassB 实例作为“this”绑定(bind)传递时?

var ClassA = function() {
//this function is totally empty
};

ClassA.prototype = {
jump: function() {...some code...},
dance: function() {
if (this.canDance) {
alert("dance");
}
}
};

ClassA.implementOn = function(targetClassOrObject) {
for ( var prop in ClassA.prototype ) {
targetClassOrObject[ prop ] = ClassA.prototype[ prop ];
}
};

var ClassB = function() {
this.canDance = true;
ClassA.call(this); // <------------What's the purpose of this line?
};

ClassA.implementOn(ClassB.prototype);

var instanceOfB = new ClassB();
instanceOfB.dance();

最佳答案

如果 ClassA 构造函数是空的,这里没有什么大惊奇的——调用ing ClassA 的空构造函数绝对什么都不做。

当您决定希望 ClassA 的构造函数为非空时,您会发现该行现在具有极其重要的作用:构造一个 ClassB 对象还在新构造的 ClassB 对象的上下文中调用特定于 ClassA 的构造函数行为,如果 ClassBClassA 的逻辑“子类”。

(当然,JavaScript 没有适当的“子类”,但这显然是一种尝试在该语言中实现基于类的行为。)

关于JavaScript 模式 : "copy" ClassA properties to ClassB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14837150/

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