我有一個Person構造函數將獲取或設置一個人的首,末和全名。更新 - JavaScript的「這個」沒有指向正確的對象
var Person = function(firstAndLast) {
var self = this;
this.getFirstName = function(){
var first = self.firstName || (function(){
return firstAndLast.split(' ')[0];
})();
return first;
};
this.getLastName = function(){
var last = self.lastName || (function(){
return firstAndLast.split(' ')[1];
})();
return last;
};
this.getFullName = function(){
var full = self.fullName || (function(){
var first = firstAndLast.split(' ')[0];
var last = firstAndLast.split(' ')[1];
return first + " " + last;
})();
return full;
};
this.setFirstName = function(first){
self.firstName = first;
console.log('first name is now: ' + self.firstName);
};
this.setLastName = function(last){
self.lastName = last;
console.log('last name is now: ' + self.lastName);
};
this.setFullName = function(firstAndLast){
self.fullName = firstAndLast;
console.log('full name is now: ' + self.fullName);
};
};
獲取預期方式工作...
var claude = new Person('Claude Shannon');
claude.getFullName();
但是,爲什麼沒有了以下工作?
claude.setFirstName('james');
claude.getFullName(); // "Claude Shannon"
(很顯然,我期待「詹姆斯·香農
你正在把'this'和'self'混合在一起。你可能想要簡化你的邏輯。 –
@FabianKlötzl對不起,只有在發佈後才注意到。我試圖解決它,但似乎我仍然沒有得到我預期的行爲。 –