Douglas Crockford 教了我们很多关于 js 的知识。特别是有 4 种使用函数的方式
- > 功能应用
function f() {}
f();
- > 方法调用
var obj = {f: function (){}};
obj.f();
- > 应用模式
var obj = {};
function f(){}
f.apply(obj);
- > 构造函数调用
function Person(){}
new Person();
我的问题是因为使用 Function 应用程序时的 this 参数是全局对象。难道它实际上只是一种特殊的方法创新。
例如
function f(){}
this.f(); // acts exactly like calling f();
看来真的只有3种模式。函数应用程序实际上并不存在。
最佳答案
It seems there are really only 3 patterns. Function Application doesn't actually exist.
确实如此,因为 f();
使用默认的 this
即使 this
在您运行它的上下文中不是默认this
。
例如:
var global = this;
var obj = {
method: function() {
console.log(this === global); // false
f();
function f() {
console.log(this === global); // true
}
}
};
obj.method();
换句话说:您的断言仅在全局范围内为真。
我在上面说“默认的 this
”是因为默认的 this
会根据您处于严格模式还是松散模式而有所不同。在严格模式下,它是 undefined
。在松散模式下,它是对全局对象的引用。
Isn't it effectivly just a special Method Inovcation.
把它倒过来:JavaScript doesn't have methods .它具有函数,以及调用将this
设置为各种值的函数的方法。 其中一种方法将 this
设置为引用具有函数引用的属性所来自的对象(例如,obj.foo()
) .
关于javascript - javascript中的函数调用总是一个方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30406107/