gpt4 book ai didi

使用原型(prototype)的Javascript继承,什么是实用的方法?

转载 作者:行者123 更新时间:2023-11-29 15:33:43 24 4
gpt4 key购买 nike

我一直在阅读 Javascript 中的继承,并想出了创建构造函数和定义每个构造函数原型(prototype)的方法。我创建了一个 prototypeExtend 函数,它将遍历每个构造函数原型(prototype)并将它们添加到主构造函数原型(prototype)中。

这是实现继承的实用方法吗?

function prototypeExtend() {
var cMain = arguments[0].prototype;
for(var i=1; i<arguments.length; i++){
var cTemp = arguments[i].prototype;
for(var k in cTemp){
if(cTemp.hasOwnProperty(k)){
cMain[k] = cTemp[k];
}
}
}
return cMain;
}

function Class1 () {}
Class1.prototype = {
el1:null,
fun1:function(str){
console.log(str + " from Class1");
},
setEl1:function(value){
this.el1 = value;
},
getEl1:function(){
return this.el1;
}
}

function Class2(){}
Class2.prototype = {
el2:"blah",
fun2:function(str){
console.log(str + " from Class2");
}
}

function Class3(){}
Class3.prototype = {
el3:"dah",
fun3:function(str){
console.log(str + " from Class3");
},
fun1:function(str){
console.log(str + " from Class3");
}
}
prototypeExtend(Class2, Class1, Class3);
var obj = new Class2;
console.log(obj);

最佳答案

在这种状态下,我能想到一些你可能看不到的东西。您直接在原型(prototype)描述中为对象的属性提供默认值。请记住,对象(和函数)将通过引用传递,因此这些属性将是静态的,如果我可以引用 Java。对该对象的任何更改都会影响所有其他引用。

当您需要覆盖函数并且仍然使用父函数时,您还必须更改代码。

如果您的目标是开发自己的库,请牢记这一点并继续! ;)无论如何,您应该看看其他人在网上做什么。我个人一直在使用 classjs它为我完成了工作!

关于使用原型(prototype)的Javascript继承,什么是实用的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31857053/

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