[英]Javascript parasitic constructor seems failed to add a function to object, why
I get this example from internet, using parasitic constructor to build an object, including giving it an extra function: 我从互联网上得到了这个示例,使用寄生构造函数来构建对象,包括为其提供额外的功能:
function SpecialArray(){
var values=new Array();
values.push.apply(values, arguments);
values.toPipedString=function(){
return this.join("|");
}
}
var colors=new SpecialArray("red", "blue", "green");
console.log(colors.toPipedString());
Well the code runs with an exception: 代码运行良好,但有一个例外:
console.log(colors.toPipedString());
^
TypeError: colors.toPipedString is not a function
But I think I've attached the function to the object. 但是我想我已经将该函数附加到对象上了。 Why it says function is not there?
为什么说功能不存在?
Thanks. 谢谢。
You attaching toPipedString function to internal var. 您将toPipedString函数附加到内部变量。 Try this:
尝试这个:
function SpecialArray() {
var values=new Array();
values.push.apply(values, arguments);
this.toPipedString = function() {
return values.join("|");
}
}
var colors = new SpecialArray("red", "blue", "green");
console.log(colors.toPipedString());
If you wanted to call toPipedArray
as a function of specialArray, it needs to be on the prototype of special array. 如果要调用
toPipedArray
作为toPipedArray
的函数,则它必须在special数组的原型上。
function SpecialArray(){
this.values=new Array();
this.values.push.apply(this.values, arguments);
}
SpecialArray.prototype.toPipedString = function(){
return this.values.join("|");
}
var colors=new SpecialArray("red", "blue", "green");
console.log(colors.toPipedString());
Nosyara's approach works as well. Nosyara的方法同样有效。 Using
this.Myfunction
within the function/object puts myFunction
on the prototype as well. 在函数/对象中使用
this.Myfunction
将myFunction
放在原型上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.