本文介绍了函数中的"this"关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自ejohn.org:

Taken from ejohn.org:

function katana(){
  this.isSharp = true;
}
katana();
assert( isSharp === true, "A global object now exists with that name and value." );

这是事实.

有人可以解释吗?在函数内部,我们看到 this.isSharp = true ,不是创建 object ,该对象应具有适当的 isSharp ,其值应为是 true ?(我认为该对象是katana,因为它调用了函数,所以 katana.isSharp 将是 true ).换句话说, this 到底指的是什么?

Could anyone explain this?Inside the function we see this.isSharp = true, doesn't that create an object which should have the propery isSharp, and its value would be true? (I would think the object is katana, since it calls the function, so katana.isSharp would be true).In other words, what exactly does the this refer to?

为什么将 isSharp 创建为对象?

推荐答案

在JavaScript中确实很奇怪.

this is really wonky in JavaScript.

this 是基于函数调用周围的上下文确定的,而不是作为函数的属性确定的.如果这样调用函数:

this is determined based on the context surrounding a function call, not as a property of the function. If a function is called like this:

f()

然后 this 将引用全局对象.如您所见,向全局对象添加属性等效于添加全局变量.如果这样调用函数:

then this will refer to the global object. Adding a property to the global object is equivalent to adding a global variable, as you saw happen. If a function is called like this:

foo.f()

然后 this 将引用 foo .示例:

> function printx() { console.log(this.x); }
> x = 300
> obj1 = {x: 20, printx: printx};
> obj2 = {x: 50, printx: printx};
> printx();
300
> obj1.printx();
20
> obj2.printx();
50

最后,如果这样调用函数:

Finally, if a function is called like this:

new f()

然后创建一个新对象, this 引用该新对象,表达式 new f()求值到该新对象或该对象返回的值如果 f()返回对象,则为 f().

then a new object is created, this refers to that new object, and the expression new f() evaluates to either that new object, or the object returned by f() if f() returns an object.

一切都在规格中.很奇怪.

It's all in the spec. Very weird.

这篇关于函数中的"this"关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 04:22