Search code examples
javascriptconstructorprototypecreation

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.


Solution

  • You attaching toPipedString function to internal var. 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());