Javascript 函数中 var 和 this 的区别? [英] Difference between var and this in Javascript functions?

查看:19
本文介绍了Javascript 函数中 var 和 this 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

vartools.triangle 中创建一个局部变量.变量originXoriginY 不能在tools.triangle 之外与外部交互.this 是指向您正在处理的当前对象的指针.第二个示例可用于通过执行 new tools.triangle(); 为对象赋予属性.如果不使用new而只使用tools.triangle();this将指向全局对象,即window 对象.您可以使用函数方法 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

重要的是要知道 this 可以引用任何对象,以及在 ES5 严格模式下是 undefined 或 null.

It is important to know that this can reference any object, as well as be undefined or null in ES5 strict mode.

您可以在此处找到更多信息.

You can find more information here.

这篇关于Javascript 函数中 var 和 this 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆