【发布时间】:2015-08-17 16:58:12
【问题描述】:
我在下面有一些代码。我不明白的问题是为什么我不必通过 this.children 引用 'children' 对象但是然后访问名字或姓氏,我必须使用 this.firstname....
请帮助我理解原因。
function User(first, sur) {
var firstName;
var surName;
var age;
var children = [];
this.firstName = first;
this.surName = sur;
this.getDisplayName = function() {
return this.firstName + ' ' + this.surName;
};
this.getTotalLength = function() {
return (this.firstName.length + this.surName.length);
};
this.displayFullName = function() {
return (this.firstName + ' ' + this.surName);
};
this.changeMaidenname = function(newSurname) {
if (newSurname)
{
this.surName = newSurname;
}
};
this.addChild = function(childUser) {
children.push(childUser);
};
this.numberOfChildren = function() {
return children.length;
};
this.killChild = function(childUser) {
children.forEach(function(item,index)
{
if (item.firstName === childUser.firstName && item.surName === childUser.surName)
{
children.splice(index, 1);
}
}
)
};
};
module.exports.User = User
【问题讨论】:
-
firstName和this.firstName都是现存的标识符,但您不会将值存储在firstName中(而您确实将值存储在this.firsName中)。
标签: javascript scope this