//使用new 關(guān)鍵字創(chuàng)建, 使用字面量創(chuàng)建
//工廠模式
function factory (){
function creatGf(name, bar){
var o = new Object()
o.name = this.name
o.bar = this.bar
o.sayWhat = function(){
alert(this.name + ', i love you')
}
return o
}
var gf1 = creatGf('mimi', 'c')
var gf2 = creatGf('bingbing', 'c')
}
//構(gòu)造函數(shù)方法
function constructor(){
function Gf(name, bar){
this.name = name
this.bar = bar
this.sayWhat = function(){
alert(this.name + ', i love you')
}
}
var gf1 = new Gf('mimi', 'c')
var gf2 = new Gf('bingbing', 'c')
console.log(gf1.sayWhat() == gf2.sayWhat()) //error, 這里調(diào)用同一個方法,卻聲明了不同的實例,浪費(fèi)資源
}
//一種改進(jìn), 將方法在外部聲明
function newConstructor(){
function Gf(name, bar){
this.name = name
this.bar = bar
this.sayWhat = sayWhat
}
function sayWhat(){
alert(this.name + ', i love you')
}
var gf1 = new Gf('mimi', 'c')
var gf2 = new Gf('amin', 'c')
console.log(gf1.sayWhat() == gf2.sayWhat()) //true, 新的問題, 方法sayWhat()沒法直接調(diào)用
}
function construcotr_prtotype(){
function Gf(name, bar) {
this.name = name
this.bar = bar
}
Gf.prototype = {
constructor: Gf,
sayWhat: function(){
alert(this.name + ',i love you')
}
}
var gf1 = new Gf('amin', 'c')
var gf2 = new Gf('beautiful girl', 'c')
}
//錯誤示例, 第二次實例化時更改了prototype的內(nèi)容
function test(){
function Gf(name, bar){
Gf.prototype.name = name
Gf.prototype.bar = bar
Gf.prototype.sayWhat = function(){
alert(this.name + ', i love you')
}
}
var gf1 = new Gf('zx', 'c')
var gf2 = new Gf('minmin', 'b')
console.log(gf1.__proto__) //{bar: 'b', name: 'minmin'}
console.log(gf1.name == gf2.name) // true
}
test()
//prototype 提供了一套方案: 同一個構(gòu)造函數(shù)實例化不同的對象時,這些對象如何共享一些屬性和方法
代碼示例絕大部分轉(zhuǎn)自segmentFualt 繆斯的情人
原文地址