我写了以下代码
1.
function Car() {
this.make = "BMW"
}
var x = new Car().make
alert(x)结果:显示警力宝马
2.
function Car() {
this.make = "BMW"
}
var x = Car().make //removed new keyword
alert(x)结果:没有显示出警戒线宝马。控制台中的错误“无法读取未定义的属性'make‘”
3.
function Car() {
this.make = "BMW"
return this //added return
}
var x = Car().make //removed new keyword
alert(x)结果:显示警力宝马
有人能解释一下吗,当我还回“这”的时候,到底发生了什么?
发布于 2015-07-26 15:27:13
当您在函数中调用Car() (没有new操作符)时,this引用全局上下文(例如,在浏览器中的window )。当您return this;时,您将返回全局对象。您还会发现,您的函数将全局对象的make属性设置为"BMW" (也就是说,alert(Car().make)后面跟着alert(make) )应该警告相同的事情两次。如果没有return this;,函数的默认返回值是undefined。
使用new运算符时,将创建一个新对象,并在其执行时绑定到函数内的this。new操作符返回构造函数返回的任何内容,如果构造函数不返回任何内容,则返回新对象。有关此问题的更多信息,请参见医生们。
https://stackoverflow.com/questions/31638654
复制相似问题