Javascript 对象,特别是 this 关键字 [英] Javascript Objects, specifically this keyword

查看:56
本文介绍了Javascript 对象,特别是 this 关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 javascript 并且正在努力理解对象,尤其是this"关键字.我已经浏览了 W3schools 上的教程并搜索了 youtube,希望有人能提供关于 javascript 中this"的很好的教程.

I am currently learning javascript at the moment and am struggling to understand objects, especially the "this" keyword. I have gone through tutorials on W3schools and searched youtube and would like if someone could provide a good tutorial on "this" in javascript.

推荐答案

忽略 Function.prototype.bind,在 ES5 中引入,this的值由函数的调用方式决定.

Ignoring Function.prototype.bind, introduced in ES5, the value of thisis set by how a function is called.

如果使用非限定标识符调用函数,例如

If a function is called with an unqualified identifier, e.g.

foo();

然后在进入函数时,thisundefined.在非严格模式下,它将被设置为全局对象(浏览器中的窗口)或在严格模式下它将保持为 undefined.

then on entering the function, this is undefined. In non-strict mode, it will be set to the global object (window in a browser) or in strict mode it will remain as undefined.

如果一个函数作为一个对象的方法被调用,例如

If a function is called as a method of an object, e.g.

someObj.foo();

然后它的this被设置为对象.

then its this is set to the object.

如果使用new 操作符,它的 this 被设置为一个新的 Object,就像由 new Object() 创建一样.

If a function is called using the new operator, its this is set to a new Object created as if by new Object().

function Foo(name) {
    this.name = name; // this references a new Object
}

如果使用call申请,那么它的 this 可以在非严格模式下设置为任何对象,或者在严格模式下设置为任何值(甚至为 null).

If a function is called using either call or apply, then its this can be set to any object in non–strict mode or to any value at all in strict mode (even null).

所以 this 与执行上下文、范围或其他任何事情都无关.它完全与如何调用函数或如何使用 bind 设置值有关.

So this has nothing to do with execution context, scope, or anything else. It is entirely related to how a function is called or how the value is set using bind.

关于监听器中的 this,这里已经回答了:onClick 函数this"返回窗口对象

In regard to this in listeners, it's been answered here: onClick Function "this" Returns Window Object

动态附加的侦听器是相似的,但在旧版 IE 中也有一些怪癖需要处理,这些问题在附加侦听器的文章中有所介绍.

Dynamically attached listeners are similar, but again there are quirks to deal with in older IE that are dealt with in articles on attaching listeners.

这篇关于Javascript 对象,特别是 this 关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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