javascript的prototype和new的一个问题
PHP中文网
PHP中文网 2017-04-10 15:03:59
0
2
311
    function Foo() {
        this.name="2"; 
    }
    Foo.prototype.method = function() {
        console.log(this.name);//1
        console.log(this);// Foo { name="1", method=function()}
    }; 
    function Bar() { 

    }
    Bar.prototype = Foo.prototype;  
    var a = new Bar();
    a.name = "1";
    a.method();
哪位能指点一下这段代码,为什么输出this指向Foo,同时为什么this也有了个name=“1”的属性
PHP中文网
PHP中文网

认证0级讲师

reply all(2)
巴扎黑
  1. 为什么输出this指向Foo?
    运行了题主的代码,发现出现的是Bar而不是Foo
  2. 为什么this也有了个name=“1”的属性?
    Bar构造函数添加了一个属性name = 1
巴扎黑

反对 @_我已经从中二毕业了 同学的关于 this 指向的回答。

this 是指向了 a,不要被控制台展示的内容欺骗了。

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template