2017-04-15 40 views
-1

我試圖弄清楚爲什麼「this」未定義,即使賦值與Lodash一起工作(調試顯示這是指預期的函數):TypeError:無法使用ES6設置屬性'emailIsValid'undefined使用ES6

創作:

validPerson = new Person({ 
     first: "Test", 
     last: "User", 
     email: "[email protected]" 
    }) 

人模塊:

import _ from 'lodash' 

let pesron = (args) => { 

    _.assignIn(this, args); 

    this.emailIsValid =() => { 
    return this.email && this.email.length > 3 && this.email.indexOf('@') > -1; 
    }; 

}; 

export default person; 

錯誤:

TypeError: Cannot set property 'emailIsValid' of undefined 

再次,_.assignIn按預期工作。

回答

1

您正在使用箭頭功能,並且this被禁止。 箭頭函數不能用作構造函數。

瞭解更多關於箭頭功能here

使用一個普通函數:

let pesron = function(args) { 

    _.assignIn(this, args); // this is now bound the current function 

    this.emailIsValid =() => { 
    return this.email && this.email.length > 3 && this.email.indexOf('@') > -1; 
    }; 

}; 

當調用new你需要有一個構造函數。例如使用ES6:

class Person { 
    constructor(name, last, email){ 
    this.first = name; 
    this.last = last; 
    this.email = email; 
    } 

    emailIsValid() { 
    return this.email && this.email.length > 3 && this.email.indexOf('@') > -1; 
    }; 

}; 

const p = new Person("Jonathan","Dion", "[email protected]") 

console.log(p.first) // Jonathan 
console.log(p.emailIsValid(p.email)) // true