Javascript寄生构造函数似乎没有向对象添加函数,为什么?

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

本文关键字:添加 对象 函数 为什么 构造函数 寄生 Javascript      更新时间:2023-09-26

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

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函数附加到内部var。试试这个:

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 array的原型上。

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的方法也有效。在函数/对象中使用this.MyfunctionmyFunction也置于原型中。