[JS]同事看了我做的this笔记,直摇头,坦言:我还是参考启发博文吧
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
在JavaScript中,this
的值是在运行时基于函数的调用方式动态绑定的。它可以指向全局对象、当前对象或者任意对象,这取决于函数调用的模式。通常,this
的值在函数定义时是无法确定的,只有在函数调用时才能确定其值。
为了更好地理解和使用this
,你可以遵循以下几个原则:
- 函数调用模式:
this
指向全局对象(在浏览器中是window
)。 - 方法调用模式:
this
指向调用方法的对象。 - 构造器调用模式:
this
指向新创建的对象。 - 上下文调用模式:可以通过
call
、apply
或bind
方法改变this
的值。
下面是一个使用this
的简单例子:
function introduce() {
return 'Hello, I am ' + this.name;
}
var person = {
name: 'Alice',
introduceSelf: introduce
};
console.log(person.introduceSelf()); // 输出: Hello, I am Alice
在这个例子中,introduce
函数使用 this.name
来访问对象的 name
属性。当 introduceSelf
方法被调用时,this
指向 person
对象,因此函数能正确地访问到 person
对象的 name
属性。
评论已关闭