`f()`和`new f()`有什么区别? [英] What's the difference between `f()` and `new f()`?
本文介绍了`f()`和`new f()`有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请参阅以下代码:
function friend(name) {
return { name: name };
}
var f1 = friend('aa');
var f2 = new friend('aa');
alert(f1.name); // -> 'aa'
alert(f2.name); // -> 'aa'
f1
和 f2
?
What's the difference between f1
and f2
?
推荐答案
您的案例中的新功能并非有用。
当函数使用'this'关键字时,您只需要使用new关键字。
The new in your case isn't usefull. You only need to use the new keyword when the function uses the 'this' keyword.
function f(){
this.a;
}
// new is required.
var x = new f();
function f(){
return {
a:1
}
}
// new is not required.
var y = f();
这篇关于`f()`和`new f()`有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文