工廠方式
function Car(name, color){
let car = new Object();// 每一次通過(guò)工廠方法去創(chuàng)建一個(gè)對(duì)象
car.name = name;
car.color = color;
car.say = function(){
console.log(this.color);
}
return car;
}
var c1 = Car('xp', 'red');
var c2 = Car('BMW', 'white');
c1.say ();
c2.say ();
缺點(diǎn):
1.無(wú)法確定對(duì)象的類型(因?yàn)槎际荗bject)。
2.創(chuàng)建的多個(gè)對(duì)象之間沒(méi)有關(guān)聯(lián)严蓖。
3.這個(gè)對(duì)象的屬性name和方法say 都必須重新創(chuàng)建一次薄嫡,浪費(fèi)內(nèi)存
構(gòu)造函數(shù)
function Car(name, color){
this.name = name;
this.color = color;
this.say = function(){
alert(name);
}
}
let car = new Car('kiwi', 'red');
car.say();
缺點(diǎn):
1.多個(gè)實(shí)例重復(fù)創(chuàng)建方法,無(wú)法共享颗胡。
2.多個(gè)實(shí)例都有say 方法毫深,但均不是同一個(gè)Function的實(shí)例。
原型
function Car(){
}
Car.prototype.name = 'kiwi';
Car.prototype.color = 'red';
Car.prototype.list = new Array('a', 'b');
Car.prototype.say = function(){
console.log(this.name+'---------------------');
}
let car = new Car();
car.say();
car.name = 'jojo';
car.list.push('c');
console.log(car.name);// jojo
console.log(car.list);// 數(shù)組的引用值毒姨,Car的兩個(gè)對(duì)象指向的都是同一個(gè)數(shù)組
car.say();// a,b,c
let car2 = new Car();
car2.say();
console.log(car2.name);// kiwi
console.log(car2.list);//a,b,c
缺點(diǎn):
1.無(wú)法傳入?yún)?shù)哑蔫,不能初始化屬性值。
2.如果包含引用類型的值時(shí)手素,改變其中一個(gè)實(shí)例的值鸳址,則會(huì)在所有實(shí)例中體現(xiàn)瘩蚪。
混合原型泉懦,構(gòu)造函數(shù)
// 構(gòu)造函數(shù)
function Car(name, color){
this.name = name;
this.color = color;
this.list = new Array('a', 'b');
}
// 原型
Car.prototype.say = function(){
console.log(this.color+'---------------------');
}
let car = new Car('kiwi', 'red');
car.list.push('c');
console.log(car.list);// a, b, c
let car2 = new Car('kiwi', 'red');
console.log(car2.list);// a, b
優(yōu)點(diǎn): 這種是目前用的最多的創(chuàng)建類和對(duì)象的方式, 將方法和屬性用不同的方式封裝.
構(gòu)造函數(shù)共享實(shí)例屬性,原型共享方法疹瘦”懒ǎ可傳遞參數(shù),初始化屬性值言沐。
動(dòng)態(tài)原型邓嘹,構(gòu)造函數(shù)
// 構(gòu)造函數(shù)
function Car(name, color){
this.name = name;
this.color = color;
this.list = new Array('a', 'b');
// 屬性的方法不會(huì)被重復(fù)創(chuàng)建, 只執(zhí)行一次
if (typeof this.say != 'function'){
Car.prototype.say = function(){
console.log(this.name);
}
}
}