javascript动态原型
我想在创建时扩展一个新的JS对象,同时让其他对象传递一个参数。 这段代码不起作用,因为我只能在没有动态参数的情况下扩展对象javascript动态原型,javascript,Javascript,我想在创建时扩展一个新的JS对象,同时让其他对象传递一个参数。 这段代码不起作用,因为我只能在没有动态参数的情况下扩展对象 otherObject = function(id1){ this.id = id1; }; otherObject.prototype.test =function(){ alert(this.id); }; testObject = function(id2) { this.id=id2; }; testObject.prototype =
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();
有什么建议吗?我不太明白你想要什么,但是
otherObject.prototype.test = function () {
alert(this.id);
};
这是正确的
还有这个
testObject.prototype=新的其他对象(id2)
除非之前设置了id2,否则将无法工作
试试下面的方法
var OtherObject = function () {
}
OtherObject.prototype.test = function () {
alert (this.id);
}
var TestObject = function (id) {
this.id = id;
}
TestObject.prototype = new OtherObject ();
var a = new TestObject("variable");
a.test ();
修正了你的代码
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"
你会在网上找到很多关于这方面的教程
testObject = function(id2) {
otherObject.call(this, id2); // run the parent object constructor with id2 parameter
this.id=id2;
};
testObject.prototype = new otherObject(); // no id2 parameter here, it doesn't make sense
请注意,在创建testObject
的实例时,调用otherObject
的构造函数两次-一次用于创建原型,一次用于初始化对象
为了防止重复初始化,我们可以在仅使用构造函数创建原型时立即停止构造函数
otherObject = function(id1){
if (typeof id1 == 'undefined') {
/* as there is no parameter, this must be the call used to create
* the prototype. No initialisation needed here, we'll just return.
*/
return;
}
this.id = id1;
};
注意:请将大写camelcase与对象一起使用。使用调试器并查找语法错误阅读:简单地修复语法和引用错误会使其发出警报
“variable”
。不太令人兴奋OtherObject应该扩展TestObject根本不需要调用构造函数来创建原型对象!第19行:未捕获的JavaScript运行时异常:TypeError:无法在object[object]中找到函数测试,但Eclipse JS无法看到object.Prototype=new()这样的继承@小鬼:不,当然不是。如果你想支持他们,有导入。。。