在Javascript函数中var和this之间的区别? [英] Difference between var and this in Javascript functions?
问题描述
var tools = {};
tools.triangle = function() {
var originX = 0;
var originY = 0;
}
var tools = {};
tools.triangle = function() {
this.originX = 0;
this.originY = 0;
}
这两个代码块之间是否有任何差异?很抱歉,如果之前已经询问过。
Are there any differences between these two code blocks? Sorry if this has been asked before.
推荐答案
var
创建一个本地变量 tools.triangle
。变量 originX
和 originY
无法与 tools.triangle $ c之外的人交互$ C>。
此
是指向您正在处理的当前对象的指针。第二个示例可用于通过 new tools.triangle();
为对象提供属性。如果你不使用 new
,只需使用 tools.triangle();
, this
将指向全局对象,即窗口
对象。您可以使用函数方法更改此
指向的对象 call();
和 apply();
如下:
var
creates a local variable within tools.triangle
. The variables originX
and originY
cannot be interacted with outside of tools.triangle
. this
is a pointer to the current object you are dealing with. The second example can be used to give properties to an object by doing new tools.triangle();
. If you do not use new
and just use tools.triangle();
, this
will point the global object which is the window
object. You can change the object to which this
points by using the function methods call();
and apply();
like this:
var myObj = {};
tools.triangle.call( myObj );
// "this" in tools.triangle now points to myObj
// myObj now has the properties originX and originY
重要的是要知道这个
可以引用任何对象,以及未定义或 null
在ES5严格模式下。
It is important to know that this
can reference any object, as well as be undefined or null
in ES5 strict mode.
您可以找到更多信息 here 。
这篇关于在Javascript函数中var和this之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!