js面向对象

前段时间刷知乎看到一个面试题,要讲讲原型链、构造函数、对象之间的联系,特地拿出红宝书整理出思维导图,加深下印象。


js面向对象_第1张图片
面向对象.png

关于继承的三个方式的代码,由于篇幅较长,不便写在原型中,所以以下整理出来。
1、原型链继承

function Chinese(){
  this.hairColor = 'black';
}
Chinese.prototype.getHairColor = function(){
  return this.hairColor;
}
function Coder(){
  this.hairColor = 'white';
}
//继承了Chinese
Coder.prototype = new Chinese();
Coder.prototype.getHairColor = function(){
  return this.hairColor;
}
var coder1 = new Coder();
alert(coder.getHairColor());     //white

例子中实例、构造函数及原型的联系如图:

js面向对象_第2张图片
原型链.png

2、借用构造函数继承

function Chinese(){
  this.hairColor = ['black','blue','green'];
}
function Coder (){
  //继承了Chinese
  Chinese.call(this);
}
var coder1 = new Coder();
coder1.color.push("white");
alert(color1.color);  //"black, blue, green, white"
var coder2 = new Coder();
alert(coder2.color);  //"black, blue, green"

3、组合继承

function Person(name){
  this.name = name;
}
Person.prototype.sayName = function(){
  alert(this.name);
}
function Children(name, age){
  //继承属性
  Person.call(this, name);
  this.age = age;
}
//继承方法 
Children.protoType = new Person();
Children.protoType.sayAge = function(){
  alert(this.age);
}
var children1 = new Children("Nicholas", 9);
children1.sayName();       //"Nicholas"
children1.sayAge();           //9
var children2 = new SubType("Wendy", 10);
children2.sayName();      //"Wendy"
children2.sayAge();          //10

剧终。。。
『写得不好的地方请大胆吐槽,非常感谢大家带我进步。』

你可能感兴趣的:(js面向对象)