1. 程式人生 > >箭頭函數無法使用this的解決方法

箭頭函數無法使用this的解決方法

減少 原因 prototype say var cnblogs 但是 使用 itl

ES6中箭頭函數 () => { } ,看到這麽簡單的寫法,我也是很喜歡用的。但是如果想在箭頭函數裏面使用this,那麽就會出現獲取不到當前對象,而是獲取到window對象。

下面這個是ES5中原型鏈上添加了一個say函數,在函數內打印出this對象,運行後能夠得到正確 Person {name: "小米", age: 7}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>箭頭函數與this</title>
</head>
<body>
    <script>
        function Person(name,age){
            
this.name = name; this.age = age; } Person.prototype.say = function(){ console.log(this); } var xiaomi = new Person(小米,7); xiaomi.say(); //Person {name: "小米", age: 7} </script> </body> </html>

好了,那麽如果使用箭頭函數呢,這裏直接將say改成箭頭函數。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>箭頭函數與this</title>
</head>
<body>
    <script>
        function Person(name,age){
            this.name = name;
            this.age = age;
        }
        Person.prototype.say 
= () => { console.log(this); } var xiaomi = new Person(小米,7); xiaomi.say(); // window </script> </body> </html>

打印出來的this直接顯示是window對象,這顯然不符合要求,為什麽會變成window對象呢,原因是箭頭函數這個 => 後面的這個花括符( { } )不是一個function作用域

那麽到這裏應該如何去獲得,這裏采用缺啥補啥的方法(將缺少的對象傳入)--簡單粗暴但有效。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>箭頭函數與this</title>
</head>
<body>
    <script>
        function Person(name,age){
            this.name = name;
            this.age = age;
        }
        Person.prototype.say = (self) => {
            console.log(self);
        }
        var xiaomi = new Person(小米,7);
        xiaomi.say(xiaomi); // Person {name: "小米", age: 7}
        xiaomi.food = 面包;
        Person.prototype.eat =(self) =>{
            console.log(self.name + 正在吃 + self.food);
        }
        xiaomi.eat(xiaomi); //小米正在吃面包
    </script>
</body>
</html>

所以看到這裏,知道箭頭函數的局限性後,建議減少使用箭頭函數,避免出現不必要的錯誤。

箭頭函數無法使用this的解決方法