我想在下面的代码中为apple创建多个实例。如何实现它。我不想改变我的对象定义风格。
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
提前致谢。
答案 0 :(得分:2)
我建议用于创建实例的构造函数:
function apple(type, color){
this.type = type;
this.color = color;
}
apple.prototype.getInfo = function(){
return this.color + ' ' + this.type + ' apple';
};
var apple1 = new apple('mac', 'red');
apple1.getInfo();
答案 1 :(得分:1)
您可以使用此
function giveMeApple() {
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
return apple;
}
var apple1 = giveMeApple();
var apple2 = giveMeApple();
// Do something with apples
答案 2 :(得分:1)
您可以使用Object.create:
Object.create()方法使用指定的方法创建一个新对象 原型对象和属性。
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
var otherApple = Object.create(apple);
如果你需要支持< IE 9,上面的链接包含一个polyfill。
答案 3 :(得分:0)
通常,这将是构造函数派上用场的情况。 Johan's answer包含这些内容。但是因为你不想改变你的对象:这里你有另一个答案。
除answer of blunderboy外,您还可以克隆该对象。没有本地功能,但很容易自己写一个。
function cloneObject(obj) {
var obj2 = {},
i;
// Take every property of obj
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// And give obj2 the same property with the same value
obj2[i] = obj[i];
}
}
}
apple2 = cloneObject(apple);
答案 4 :(得分:0)
var Apple = function () {
var AppleType = null;
var AppleColor = null;
var self = this;
var OutPutAppleInfo = function () {
var String = 'My Apple is ' + AppleType + ' And It Is ' + AppleColor + ' In Color.';
console.log(String);
}
return {
SetAppleColor: function (obj) {
AppleColor = obj;
},
SetAppleType: function (obj) {
AppleType = obj;
},
PrintAppleInfo: function () {
OutPutAppleInfo();
}
};
}
function Init()
{
var Apple1 = new Apple();
var Apple2 = new Apple();
var Apple3 = new Apple();
Apple1.SetAppleColor('Yellow');
Apple2.SetAppleColor('Green');
Apple3.SetAppleColor('Red');
Apple1.SetAppleType('macintosh');
Apple2.SetAppleType('Food');
Apple3.SetAppleType('Model');
console.log('Apple1');
Apple1.PrintAppleInfo();
console.log('Apple2');
Apple2.PrintAppleInfo();
console.log('Apple3');
Apple3.PrintAppleInfo();
}