html - JavaScript 中,如果 function 中使用了 return this,外部为什么就不用写 new 了?
本文介绍了html - JavaScript 中,如果 function 中使用了 return this,外部为什么就不用写 new 了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
这是第一种:
function ren()
{
//声明属性:
this.name="二狗";
this.age=28;
this.sex="男";
//声明方法:
this.say=function(){
console.log("我的名字是"+this.name+",性别是"+this.sex+",年龄是"+this.age+"...");
}
}
//模拟类:
var p1 = new ren();
//调用方法:
p1.say();
//查看属性:
console.log(p1.name);
这是第二种:
function ren()
{
//声明属性:
this.name="二狗";
this.age=28;
this.sex="男";
//声明方法:
this.say=function(){
console.log("我的名字是"+this.name+",性别是"+this.sex+",年龄是"+this.age+"...");
}
return this;
}
//模拟类:
var p1 =ren();
//调用方法:
p1.say();
//查看属性:
console.log(p1.name);
这个结果 是一样的,就是第一个 在 function 的结尾加了个 return this;
在外部少写了个 new ;
这是为什么呢?
解决方案
函数调用时内部的this
默认指向全局对象. 就是说题主例子里的this.name="二狗";
都为全局变量声明, 函数最后返回的this === window
(浏览器端). 你可以在函数调用后试试以下代码
console.log(age);
console.log(p1 === window);
这篇关于html - JavaScript 中,如果 function 中使用了 return this,外部为什么就不用写 new 了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文