gpt4 book ai didi

javascript - 解释这个Uncaught TypeError : Property 'x' of object [object Object] is not a function

转载 作者:行者123 更新时间:2023-12-03 16:44:17 24 4
gpt4 key购买 nike

有人可以解释为什么我在以下每种情况下都会得到结果吗?如果这是问题所在,我想了解为什么结果是关于 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());

如果我将 addSalaryFunction 移动到 Employees 函数中,在 this.addSalary 下方,我会得到 Uncaught 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.addSalary 上方,如果再次正常工作。尽管我的 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());

最佳答案

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

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;
}

关于javascript - 解释这个Uncaught TypeError : Property 'x' of object [object Object] is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16609962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com