【发布时间】:2017-10-19 09:24:53
【问题描述】:
谁能解释一下为什么在“setFirstName”设置器方法将“firstName”变量更改为“NewFirstName”后我的对象中的“fullName”变量没有改变。我知道这个问题的正确答案,但我很困惑为什么以下解决方案也不起作用。
This is a picture showing the below snippet being run
代码如下:
<!DOCTYPE html>
<html>
<script>
var Person = function(firstAndLast) {
let firstName = firstAndLast.split(" ")[0];
let lastName = firstAndLast.split(" ")[1];
let fullName = firstName + " " + lastName;
// Getters
this.getFirstName = function() {
return firstName;
};
this.getLastName = function() {
return lastName;
};
this.getFullName = function() {
return fullName;
};
// Setters
this.setFirstName = function(first) {
firstName = first;
};
this.setLastName = function(last) {
lastName = last;
};
this.setFullName = function(name) {
fullName = name;
};
};
debugger;
var bob = new Person('Bob Ross');
console.log(bob.getFullName());
bob.setFirstName("NewFirstName");
console.log(bob.getFirstName());
console.log(bob.getFullName());
</script>
</html>
【问题讨论】:
-
您的
fullname变量在实例化期间被评估一次。您可能希望从 getter 返回firstname + ' ' + lastname而不是fullname本身。
标签: javascript oop object constructor