【问题标题】:Javascript - Scope and ThisJavascript - 范围和这个
【发布时间】: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

【问题讨论】:

  • firstNamethis.firstName 都是现存的标识符,但您不会将值存储在 firstName 中(而您确实将值存储在 this.firsName 中)。
  • Here你可以阅读更多关于模块模式和here关于这个关键字的信息

标签: javascript scope this


【解决方案1】:

在 js 中,this 关键字用于创建公共变量,而 var 将该变量的范围限制为该特定函数。 :)。除非定义 this.children=[]

,否则您甚至无法访问子对象

【讨论】:

    猜你喜欢
    • 2011-06-08
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 2018-10-17
    • 2013-10-03
    • 1970-01-01
    • 2021-01-21
    相关资源
    最近更新 更多