【发布时间】:2020-05-12 15:42:36
【问题描述】:
function Person(name, age, gender) {
this.name = name; // run
}
function PersonSafe(name) {
if (!(this instanceof arguments.callee))
return new PersonSafe(name)
this.name = name; // run
}
var qux = Person('qux');
console.log('Person qux: ', qux);
console.log('[[global]] name: ', name);
var quxSafe = PersonSafe('qux');
console.log('PersonSafe qux: ', quxSafe);
在没有new关键字的情况下调用constructor时的两种情况的比较。
我不知道为什么两个代码运行的结果不同。body 和Person() 和PersonSafe() 的功能不同,
但qux 和quxSafe 将执行的行(this.name = name;)是相同的。
那么...为什么结果不同?
【问题讨论】:
-
stackoverflow.com/questions/8205691/array-vs-new-array 如果您想找出使用 new 和不使用 new 之间的区别。
-
在没有
new的情况下调用函数只会像执行任何其他函数一样执行它。Person不包含return语句,因此它返回undefined。 -
@Tick20 您好,感谢您的评论。但是,这两个对象是在没有
new关键字的情况下创建的。 -
@snaag
PersonSafe包含return语句。如果没有使用new调用它,它会使用new递归调用自身。这就是区别。 -
@JLRishe 哦,我的.....哦,我真的真的很笨......哇......我明白了!哇..谢谢..哈哈...