JavaScript this

本文深入解析JavaScript中this关键字的工作原理,包括其在不同上下文中的指向变化,以及如何使用call和apply来改变函数运行时的this指向。通过具体示例,帮助读者理解this在全局作用域、对象方法调用及构造函数中的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

this

this 本身原本很简单,总是指向类的当前实例。

this的特点:

  • 在 function 内部被创建
  • 函数预编译过程中,

    • this –> window(this指向window)
    • 全局作用域里this –> window
  • 指向调用时所在函数所绑定的对象

    • 谁调用这个方法,this就指向谁。obj.func(); func()里面的this指向obj)
  • this 不能被赋值,但可以被 call/apply 改变
    • call/apply可以改变函数运行时this的指向

例题:

<script type = "text/javascript"> 
    var name = "222";
    var a = {
        name : "111",
        say : function() {
            console.log(this.name);
        }
    }
    var fun = a.say;
    fun()               //222  将a.say放在全局执行
    a.say()             //111  a调用say方法
    var b = {
        name : "333",
        say : function() {
            fun();      //不像别的有调用:a.say,(前面有a.),这个没有,所以就执行预编译(全局的)
        }
    }
    b.say(a.say);          //222
    b.say = a.say;
    b.say();              //333

</script>

//222 111 222 333

练习题:

<script type = "text/javascript"> 
    var foo = 123;
    function print() {
        this.foo = 234;      //this表示的是window里面的,所以把GO的123改成了234   
        console.log(foo);    //指的是GO里面的123,但是前面有this的声明
    }
    print();                 
</script>
//234    

变形:

<script type = "text/javascript"> 
    var foo = 123;
    function print() {
        // var this = Object.create(print.prototype)  //这里的this不指代windowthis.foo = 234;      //AO里面没有foo,所以到GO里面去找 
        console.log(foo);    //指的是GO里面的123,但是前面有this的声明
    }
    new print();
</script>
//123   

例题:

运行test()和new test()的结果分别是什么?
<script type = "text/javascript"> 
    var a = 5;
    function test() {
        a = 0;
        alert(a);               //0     0
        alert(this.a);          //5     undefined
        var a;
        alert(a);               //0     0
    }
    test();
    new test();
</script>

解析:

test()
AO {
    a:undefined
    this.a:window
}
        |
 AO {
    a:0
    this.a:5
new test()
AO {
    a:undefined
    this.a:{}
}
        |

new的时候函数里面有var this = Object.create(test.prototype)
或者写成var this = {
                    __proto__:test.prototype

                   }
 AO {
    a:0
    this.a:undefined   //this上面没有a
### JavaScript 中 `this` 关键字的用法与行为 在 JavaScript 中,`this` 是一个特殊的关键字,用于指代函数执行时所在的上下文对象。它的具体指向取决于调用方式以及代码运行环境。 #### 函数内的 `this` 当在一个普通的函数内部访问 `this` 时,在非严格模式下它通常指向全局对象(浏览器中的 `window` 对象),而在严格模式下则会返回 `undefined`[^4]。 ```javascript function testFunction() { console.log(this); } testFunction(); // 非严格模式下输出 window;严格模式下输出 undefined ``` #### 方法中的 `this` 如果一个函数作为某个对象的方法被调用,则该方法里的 `this` 将自动绑定到这个特定的对象上[^5]。 ```javascript const obj = { name: 'Example', greet: function () { console.log(`Hello from ${this.name}`); } }; obj.greet(); // 输出 Hello from Example ``` #### 构造器中的 `this` 当通过 new 运算符创建实例的时候,构造器里面的 `this` 被设置成新生成的那个实例[^6]。 ```javascript function Person(name) { this.name = name; } const personInstance = new Person('John Doe'); console.log(personInstance.name); // John Doe ``` #### 箭头函数中的 `this` 箭头函数不定义自己的 `this` ,而是捕获其所在词法作用域链上的最近一层非箭头函数的作用域下的 `this` [^7]。 ```javascript const objectWithArrowFunc = { name: 'Lexical This', logNameArrow: (() => console.log(this)) }; objectWithArrowFunc.logNameArrow(); // 可能输出 global/window 或者 undefined 如果是在模块环境中 ``` #### 使用 bind/call/apply 改变 `this` 的指向 开发者可以利用 `.bind()`、`.call()` 和 `.apply()` 明确指定某次调用期间使用的 `this` 引用[^8]。 ```javascript let user = { firstName:"Alice", lastName : "Smith"}; function getFullName(title){ return `${title} ${this.firstName} ${this.lastName}`; } getFullName.call(user,"Ms."); // Ms. Alice Smith ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值