Javascript set 属性函数不起作用

Javascript set attribute function doesn't work

本文关键字:不起作用 函数 属性 set Javascript      更新时间:2023-09-26

我是Javascript和编程的乞丐,我的英语不好(对不起,如果有任何语法错误),但这是我的问题:

当我在JS中创建一个类并创建一个函数来设置其对象的属性时,浏览器无法识别该函数。 示例:

var myObject = new MyClass();
myObject.setAttribute();
function MyClass() {
    this.attribute;
}
MyClass.prototype.setAttribute = function() {
    this.attribute = true;
};

当我尝试运行此代码时,chrome 会抛出一个错误,说"未捕获的类型错误:对象 # 没有方法'setAtributte'",指定的行为 2。我不明白。

再说一遍:我是一个乞丐,所以这对你来说可能是一个愚蠢的错误,但这对我来说是一个很大的问题。 谢谢。

JavaScript 已经"提升"了你的声明,以便在变量声明之前定义MyClass;但是你的原型更新没有被提升。更改代码的顺序

function MyClass() {
    this.attribute;
}
// Prototype has to be defined BEFORE it can be used
MyClass.prototype.setAttribute = function() {
    this.attribute = true;
    console.log(this.attribute);
};
var myObject = new MyClass();
myObject.setAttribute();

使用 function name() {} 语法声明的函数被提升在顶部,这允许您在代码中定义函数之前调用函数,但对于其他每行都不正确。

您的代码基本上被评估为:

var MyClass = function MyClass() {
    this.attribute;
}
var myObject = new MyClass();
myObject.setAttribute(); //does not exist since it's defined on the line below
MyClass.prototype.setAttribute = function() {
    this.attribute = true;
};

您应该将代码重新排序为:

//constructor declaration
//setting prototype values
var myObject = new MyClass();
myObject.setAttribute('test');