2

有人可以解释为什么我在以下每种情况下都会得到我的结果吗?如果这是问题所在,我想了解为什么结果是关于 JavaScript 如何与范围一起工作的结果。在第一个示例中,我的代码运行正常。

var Employees = function(name, salary) {
    this.name = name;
    this.salary = salary;

    this.addSalary = addSalaryFunction;

    this.getSalary = function() {
        return this.salary;
    };

};

var addSalaryFunction = function(addition) {
        this.salary = this.salary + addition;
    };


var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());

如果我将 移动addSalaryFunctionEmployees函数中,并且在下面this.addSalary我得到未捕获的 TypeError。

var Employees = function(name, salary) {
    this.name = name;
    this.salary = salary;

    this.addSalary = addSalaryFunction;

    this.getSalary = function() {
        return this.salary;
    };

    var addSalaryFunction = function(addition) {
        this.salary = this.salary + addition;
    };
};

var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());

但是如果我移动addSalaryFunction上面的this.addSalaryif 再次正常工作。尽管我的 IDE 告诉我我的局部变量addSalaryFunction是多余的。

var Employees = function(name, salary) {
    this.name = name;
    this.salary = salary;

    var addSalaryFunction = function(addition) {
        this.salary = this.salary + addition;
    };

    this.addSalary = addSalaryFunction;

    this.getSalary = function() {
        return this.salary;
    };

};


var ceo = new Employees("Chris", 400000);
ceo.addSalary(20000);
document.write(ceo.getSalary());
4

4 回答 4

7

这是因为您试图在创建函数之前对其进行分配。

this.addSalary = addSalaryFunction; // there's no function yet

//...

var addSalaryFunction = function(addition) {  // now there is, but too late
    this.salary = this.salary + addition;
};

当您将变量赋值移到 上方时this.addSalary = addSalaryFunction,您现在正在创建函数,然后再尝试引用它。

var addSalaryFunction = function(addition) {  // here's the function
    this.salary = this.salary + addition;
};
this.addSalary = addSalaryFunction;  // now we can assign it

如果您改用函数声明语法,则第一个版本将起作用,因为函数声明被“提升” (如他们所说)到变量范围的顶部。

this.addSalary = addSalaryFunction; // This now works because of the magic below

//...

// This is magically hoisted to the top
function addSalaryFunction(addition) {
    this.salary = this.salary + addition;
}
于 2013-05-17T13:17:06.423 回答
2

第二种方法不起作用,因为 addSalaryFunction 在声明之前就被引用了。

您可以删除一些代码并声明:

this.addSalary = function(addition) {
    this.salary = this.salary + addition;
}
于 2013-05-17T13:17:36.583 回答
0

以更简单的形式:

var foo = function() {
    var x = y;
    var y = 2;
    return x;
};

var bar = function() {
    var y = 2;
    var x = y;
    return x;
};

显然,bar()将返回 2. foo,但是,当它在第一行undefined查找值时获取,因此返回。虽然变量声明被提升到其范围的顶部,但变量初始化却没有。yundefined

于 2013-05-17T13:19:14.957 回答
0

这是一个特定的吊装问题。看看这个解释:http ://www.sitepoint.com/back-to-basics-javascript-hoisting/

于 2013-05-17T13:19:23.433 回答