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”的属性
第1. this
没有指向Foo
.
第2. 为什么会有name
,那是因为你new
了之后添加的(a.name="1"
).
不信的话,自己运行下面的代码
javascript
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.method();//Bar {method: function} a.name = "1"; a.method();//Bar {name: "1", method: function} a.test = '2222'; a.method();//Bar {name: "1", test: "2222", method: function}
===================Firefox
下的效果:
NodeJS
下的效果
IE
下的效果
反对 @_我已经从中二毕业了 同学的关于 this
指向的回答。
this
是指向了 a
,不要被控制台展示的内容欺骗了。
- 为什么输出this指向Foo?
运行了题主的代码,发现出现的是Bar
而不是Foo
。 - 为什么this也有了个name=“1”的属性?
给Bar
构造函数添加了一个属性name = 1
。