【发布时间】:2026-01-23 17:15:01
【问题描述】:
我读过的所有内容似乎都倾向于在原型声明中声明对象构造函数的方法,而不是将方法直接放入初始构造函数中。
function MyClass(name){
this.name = name;
}
MyClass.prototype.callMethod = function(){
console.log(this.name);
};
这会被推荐吗?如果是这样,将方法放在初始构造函数中有什么缺点。
function MyClass(name){
this.name = name;
this.callMethod = function(){
console.log(this.name);
};
}
我假设这样一个简单的情况,无论哪种方式都无关紧要,但是对于较大的对象,在两种情况下声明方法的含义是什么?
【问题讨论】:
标签: javascript methods constructor prototypal-inheritance