简体   繁体   English

JavaScript原型__proto__

[英]Javascript prototype , __proto__

When I execute below java script code I get error at "v.dummy();" 当我在Java脚本代码下执行时,出现“ 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 __proto__只是对象的引用

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). 1)在将函数分配给变量时,可以省略名称( dummy )并使用匿名函数(无名称)。 Function name is useless in this case. 函数名在这种情况下是没有用的。 And if you do 如果你这样做

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

you can call it like this: x() , not 您可以这样称呼它: x() ,而不是 y()

2) __proto__ should be an object, not a function 2) __proto__应该是对象,而不是函数

usage of foo is correct, therefore it works. foo用法是正确的,因此可以正常工作。

You may want to consider reading a good JS book. 您可能需要考虑阅读一本不错的JS书。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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