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

Javascript寄生构造函数似乎无法向对象添加函数,为什么,javascript,constructor,prototype,creation,Javascript,Constructor,Prototype,Creation,我从互联网上得到了这个例子,使用寄生构造函数构建一个对象,包括给它一个额外的函数: function SpecialArray(){ var values=new Array(); values.push.apply(values, arguments); values.toPipedString=function(){ return this.join("|"); } } var colors=new SpecialArray("red", "

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

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
但是我想我已经把这个函数附加到了这个对象上。为什么它说功能不存在


谢谢。

您正在将管道字符串函数附加到内部变量。 试试这个:

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

将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
作为SpecialRay的函数,它需要位于specialArray的原型上

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.Myfunction
也会将
Myfunction
放在原型上。

如果要将
toPipedArray
作为specialArray的函数调用,它需要放在specialArray的原型上

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.Myfunction
也会将
Myfunction
放在原型上。

values
specialray
中的本地数组,
toPipedString
是该数组的方法。
values
specialray
中的本地数组,
toPipedString
是该数组的一种方法。。。