gpt4 book ai didi

javascript 动态原型(prototype)

转载 作者:行者123 更新时间:2023-11-29 09:55:59 25 4
gpt4 key购买 nike

我想在创建时扩展一个新的 JS 对象,而其他对象传递一个参数。此代码不起作用,因为我只能扩展没有动态参数的对象。

otherObject = function(id1){
this.id = id1;
};

otherObject.prototype.test =function(){
alert(this.id);
};

testObject = function(id2) {
this.id=id2;
};

testObject.prototype = new otherObject("id2");/* id2 should be testObject this.id */


var a = new testObject("variable");
a.test();

有什么建议吗?

最佳答案

除了明显的语法错误,JavaScript正确的继承方式是这样的:

// constructors are named uppercase by convention
function OtherObject(id1) {
this.id = id1;
};
OtherObject.prototype.test = function() {
alert(this.id);
};

function TestObject(id2) {
// call "super" constructor on this object:
OtherObject.call(this, id2);
};
// create a prototype object inheriting from the other one
TestObject.prototype = Object.create(OtherObject.prototype);
// if you want them to be equal (share all methods), you can simply use
TestObject.prototype = OtherObject.prototype;


var a = new TestObject("variable");
a.test(); // alerts "variable"

你会在网上找到很多关于这方面的教程。

关于javascript 动态原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11614113/

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