// 示例代码:js this 指向
// 1. 在全局作用域中,this 指向全局对象 (浏览器中是 window)
console.log(this === window); // true
// 2. 在函数中,this 指向全局对象(非严格模式)
function foo() {
console.log(this === window); // true
}
foo();
// 3. 在严格模式下,函数中的 this 是 undefined
function bar() {
'use strict';
console.log(this === undefined); // true
}
bar();
// 4. 在对象方法中,this 指向调用该方法的对象
const obj = {
name: 'Alice',
greet: function() {
console.log(`Hello, ${this.name}`); // Hello, Alice
}
};
obj.greet();
// 5. 使用 call、apply 或 bind 可以显式指定 this 的值
function speak(message) {
console.log(`${this.name} says ${message}`);
}
const person = { name: 'Bob' };
speak.call(person, 'hello'); // Bob says hello
speak.apply(person, ['hi']); // Bob says hi
const boundSpeak = speak.bind(person);
boundSpeak('how are you?'); // Bob says how are you?
this 指向全局对象(如浏览器中的 window)。this 也指向全局对象;但在严格模式下,this 是 undefined。this 指向调用该方法的对象。this 的指向。上一篇:js 学习
下一篇:js log
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站