`f()`和`new f()`有什么区别? [英] What's the difference between `f()` and `new f()`?

查看:102
本文介绍了`f()`和`new f()`有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

JavaScript中的'new'关键字是什么?

从JS闭包创建对象:我应该使用new关键字?

请参阅以下代码:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆