function foo() {
return {a:9};
}
var bar = foo();
bar.a //returns 9
Run Code Online (Sandbox Code Playgroud)
要么
function foo() {
return {a:9};
}
var bar = new foo();
bar.a // returns 9
Run Code Online (Sandbox Code Playgroud)
据我所知,新的不是与对象文字符号一起使用,但是新的如何使用呢?另外,为什么可以使用新对象访问原型,而不是使用对象文字符号?
编辑:
我现在明白了,如果其他任何人偶然发现这个问题/问题,这可能有助于你理解它:
function foo() {
this.a = "LOL";
return "WTF";
};
var bar = new foo(); // bar = [Object object]
var c = foo(); // c = "WTF"
window.a // "LOL"
Run Code Online (Sandbox Code Playgroud)
另请阅读接受的答案.
new在这种情况下使用与你返回的内容无关,但this内在的是什么foo().使用new,this将是对foo实例内部的引用foo().没有新的,this将是全球(可能window)
它的工作原理是因为如果从作为构造函数(using new)调用的函数显式返回非基本类型,则返回该对象而不是创建的对象.您没有以任何方式在函数中使用创建的对象,因此new是多余的.
在这里你可以看到它不适用于原语:
function test() {
return "string"; //This is not returned when called with new, because it's primitive
}
var a = new test();
a == "string" // false
function test() {
return new String("string"); //This is returned when called with new, because it's an object, like {}
}
var b = new test();
b == "string" //true
Run Code Online (Sandbox Code Playgroud)
我正在使用==并new String用于演示目的.你不应该new String在实践中使用.
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |