这些是创建 javascript 对象的方法:
function apple(optional_params) {
this.type = "macintosh";
this.color = "red";
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
};
}
var apple = {
type: "macintosh",
color: "red",
getInfo: function() {
return this.color + ' ' + this.type + ' apple';
}
}
我真的更喜欢后者,因为它是 Json 语法,但我看到的第一个比后者多。
- 它们在功能上有什么区别吗?
- 能否对它们中的每一个进行扩展、继承和克隆/复制?
- 在后一个中我可以轻松创建嵌套元素,这在第一个中可行吗?
- 在后一个中我不能传递可选参数?
- 它们的用途不同吗?如果是,您能否给出我会使用其中任何一个的场景。
最佳答案
区别在于您可以重复使用第一个。示例:
function Apple(type, color) {
this.type = type;
this.color = color;
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
}
}
var red = new Apple("Macintosh", "red");
var green = new Apple("Granny Smith", "green");
对比
var red = {
type: "Macintosh",
color: "red",
getInfo: function() {
return this.color + ' ' + this.type + ' apple';
}
};
var green = {
type: "Granny Smith",
color: "green",
getInfo: function() {
return this.color + ' ' + this.type + ' apple';
}
};
关于javascript - 创建 javascript 对象的两种方法,我应该使用哪一种?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3784729/