Javascript 寄生构造函数似乎无法向对象添加函数,为什么

Javascript parasitic constructor seems failed to add a function to object, why

我从网上得到这个例子,使用寄生构造函数来构建一个对象,包括给它一个额外的函数:

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());

好吧,代码运行异常:

console.log(colors.toPipedString());
                   ^
TypeError: colors.toPipedString is not a function

但我想我已经将函数附加到对象上了。为什么说没有功能?

谢谢。

您将 toPipedString 函数附加到内部变量。 试试这个:

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());

如果你想调用toPipedArray作为specialArray的函数,它需要在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 的方法也很有效。在 function/object 中使用 this.Myfunction 也会在原型上放置 myFunction