Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js this指向

作者:幸福的起点   发布日期:2026-04-17   浏览:27

// 示例代码: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 也指向全局对象;但在严格模式下,thisundefined
  • 对象方法:当方法作为对象的属性被调用时,this 指向调用该方法的对象。
  • call、apply 和 bind:这些方法可以显式地改变函数内部 this 的指向。

上一篇:js 学习

下一篇:js log

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站