javascript动态原型

use*_*250 3 javascript

我希望在创建时扩展一个新的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();
Run Code Online (Sandbox Code Playgroud)

有什么建议吗?

Ber*_*rgi 5

除了明显的语法错误之外,正确的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"
Run Code Online (Sandbox Code Playgroud)

您将在网上找到许多关于此的教程.