Javascript - 范围和这个

时间:2015-06-03 12:59:34

标签: javascript scope this

我在下面有一些代码。我不明白的问题是为什么我不必通过this.children引用'children'对象然后访问firstname或surname,我必须使用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

1 个答案:

答案 0 :(得分:0)

在js中,此关键字用于创建公共变量,而var将该变量的范围限制为该特定函数。 :)。你甚至无法访问子对象,除非它被定义为this.children = []