//使用new 关键字创建, 使用字面量创建
//工厂模式
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')
}
//构造函数方法
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, 这里调用同一个方法,却声明了不同的实例,浪费资源
}
//一种改进, 将方法在外部声明
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()没法直接调用
}
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的内容
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 提供了一套方案: 同一个构造函数实例化不同的对象时,这些对象如何共享一些属性和方法
代码示例绝大部分转自segmentFualt 缪斯的情人
原文地址
网友评论