我试图找出原因"这个"是未定义的,即使Lodash的赋值工作(调试显示这引用了预期的函数):
创建:
validPerson = new Person({
first: "Test",
last: "User",
email: "test@test.com"
})
人员模块:
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
按预期工作。
答案 0 :(得分:2)
您正在使用箭头功能,而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@gmail.com")
console.log(p.first) // Jonathan
console.log(p.emailIsValid(p.email)) // true