考虑示例模块创建,为什么括号会更改 this
引用?
如section 11.2.2 in JavaScript specification说:
The production NewExpression : new NewExpression is evaluated as follows:
- Let ref be the result of evaluating NewExpression.
- Let constructor be GetValue(ref).
- If Type(constructor) is not Object, throw a TypeError exception.
- If constructor does not implement the
[[Construct]]
internal method, throw a TypeError exception.- Return the result of calling the
[[Construct]]
internal method on constructor, providing no arguments (that is, an empty list of arguments).
经过一番调查后,以下之间没有差异(有吗?):
console.log(new (modules.getModule('foo')).method)
console.log(new (modules.getModule('foo')).method())
在两个示例中都执行了方法
。
变得更有趣:
console.log(typeof new modules.getModule('foo').method) // function
console.log(typeof new (modules.getModule('foo')).method) // object
这些差异的根源是什么?
var modules = (function() {
var definitions = {
foo: {
method: function() {
this.thing = 'baz';
}
}
};
return {
getModule: function(name) {
if(name in definitions) {
return definitions[name];
}
}
};
}());
alert('this: ' + new modules.getModule('foo').method()) // undefined
alert('this: ' + new (modules.getModule('foo')).method()) // {this.thing = 'baz'}
最佳答案
括号不会改变 this
方法调用的引用。括号更改 NewExpression
那new
评估。
如果new
运算符位于属性链(后跟访问器的表达式)前面,它将评估该链并实例化生成的构造函数。
如果new
运算符位于调用表达式(一个表达式,可能包括访问器,后跟参数列表)前面,该调用将为 new
提供参数手术。任何尾随访问器都将访问新实例化对象的属性。
对于您的示例,这意味着
new modules.getModule ('foo') .method
new modules.getModule ('foo') .method()
// are evaluated as
(new (modules.getModule)('foo'))…
// on which then .method is accessed or called
new (modules.getModule('foo')).method
new (modules.getModule('foo')).method ()
// are evaluated as
new (( … ).method)() // the empty parentheses are optional for `new`
(modules.getModule('foo')).method
// just evaluates to the `method` function
(modules.getModule('foo').method)
关于javascript - 表达式求值 - 为什么括号会更改 "this"引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29965778/