简体   繁体   中英

Javascript prototype , __proto__

When I execute below java script code I get error at "v.dummy();" line , please let me know where am I doing wrong.

    function Test()
    {

    }

    Test.prototype.foo = function () {
        console.log('foo');
    }

    var v = new Test();

    v.foo();

    v.__proto__ = function dummy() {
        console.log('__proto__'); 
    };

    v.dummy(); // Uncaught TypeError: v.dummy is not a function

__proto__ is just a reference of an object

IMG

You can't make it equal a new function, but you can do it like this:

v.__proto__.foo = function dummy(){}

I don't know what you are trying to do, but:

1) when you assign function to a variable, you may omit the name ( dummy ) and use an anonymous function (without a name). Function name is useless in this case. And if you do

var x = function y(){ ... }

you can call it like this: x() , not y()

2) __proto__ should be an object, not a function

usage of foo is correct, therefore it works.

You may want to consider reading a good JS book.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM