LGe*_*lis 5 javascript javascript-objects
我刚刚遇到了让我感到惊讶的事情。考虑以下四个函数:
function A() {
this.q = 1;
}
function B() {
this.q = 1;
return this;
}
function C() {
this.q = 1;
return 42;
}
function D() {
this.q = 1;
return {};
}
Run Code Online (Sandbox Code Playgroud)
让我们new从所有对象中创建对象(通过):
console.log('a', new A());
console.log('b', new B());
console.log('c', new C());
console.log('d', new D());
Run Code Online (Sandbox Code Playgroud)
这是输出:
a A { q: 1 }
b B { q: 1 }
c C { q: 1 }
d {}
Run Code Online (Sandbox Code Playgroud)
前三个似乎表明函数返回什么并不重要,JS 只关心每个函数的作用this(这是我以前的信念,顺便说一句)。但最后一个与此相反。
那么,这里发生了什么?我修改后的规则是“如果函数返回一个Object,我们保留它。否则,我们保留this”。但我对此感到非常不确定。
Lor*_*nd 1
当您使用new运算符时,它会创建一个对象。
返回值符合预期。如果返回它是一个对象将返回该对象,否则如果返回它是一个函数将返回该函数。
function A(){
this.b = 3;
return function(){return 4;};
}
function B(){
this.b = 3;
return { d:4};
}
console.log(typeof (new A())); //function
console.log(typeof (new B())); //object {d:4}
Run Code Online (Sandbox Code Playgroud)
如果返回中存在任何其他值或不存在,则此运算符将优先作为对象返回。
function C(){
this.b = 3;
return "78";
}
console.log(typeof (new C())); // object {b:3}
Run Code Online (Sandbox Code Playgroud)