[英]How to create multiple instances of JS Class/Object?
我想在下面的代碼中為apple創建多個實例。 如何實現。 我不想更改我的對象定義樣式。
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
提前致謝。
我建議使用一個構造函數來創建實例:
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();
你可以用這個
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
您可以使用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。
通常,在這種情況下構造函數會派上用場。 約翰的答案就是這些。 但是,由於您不想更改對象,因此您將獲得另一個答案。
除了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);
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.