Object的prototype使用对构造函数的影响

JS中的Object有一个属性prototype 即原型函数

除了 var obj = Object.create(null);  这样的方式建立的对象没有prototypethis

在咱们使用构造函数时,prototype经常会混淆,不容易分辨prototype

经常使用的OO模式(面向对象)对象

function Parent(name){原型

  this.name = name;io

}console

Parent.prototype.say = function(){function

  return "Your name is " + this.name;构造函数

}call

function Child(name){

  Parent.call(this,name);

}

Child.prototype = Object.create(Parent.prototype);

Child.prototype.greet = function(){

  console.log("Hello,"+this.say()+".");

}

var f1 = new Child("nana");

var f2 = new Child("bobo");

f1.greet();

f2.greet();

这种经典的OO模式,有不少prototype,很容易就迷失方向了,超级思惟逻辑的人请忽略

另外一种推荐使用模式OLOO(Object Linked Other Object)

var Parent = {

  name:function(name){

    this.name = name;

  },

  say:function(){

    return "Your name is " + this.name;

  }

}

var Child = Object.create(Parent);

Child.greet = function(){

  console.log("Hello, " + this.say() + ".");

}

 

var f1 = Object.create(Child);

f1.name('anan');

var f2 = Object.create(Child);

f2.name = ("lala");

f1.greet();

f2.greet();

这种互相连接的对象,简化了执行过程,并能得获得相同结果。

相关文章
相关标签/搜索