这是第一种:
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 ;
这是为什么呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
函数调用时内部的
this默认指向全局对象. 就是说题主例子里的this.name="二狗";都为全局变量声明, 函数最后返回的this === window(浏览器端). 你可以在函数调用后试试以下代码你的第二种会有这种很有意思的现象:
目前为止都很happy
但是,我把第一个二狗改名字后:
WTF,
p2也成三胖了!!其原因就是@zin解释的。
new关键字做了什么,看看这里,就知道他是return this不能简单替代了