我想在创建时扩展一个新的 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/

10-11 22:51
查看更多