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

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

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

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

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

function Parent(name){

  this.name = name;

}

Parent.prototype.say = function(){

  return "Your name is " + this.name;

}

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();

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

猜你喜欢

转载自www.cnblogs.com/rouge-ya/p/10039157.html