prototype原型链继承

依旧是恶补js基础,上代码:dom

一、定义父类及父类方法函数

function Animal(){
    this.name = "动物";
}

Animal.prototype.eat = function(food){
    alert('eat ' + food);
}

二、定义子类测试

function Ferret(){
    this.name = "雪貂";
  //this.type = "leixing";//此处,若是定义了type,会覆盖下面prototype.type的“domestic”
  //说明一个机制,调用Ferret().type的时候,先寻找对象自有属性,再查找原型链内属性

}

三、原型链继承核心this

function fn(){
   //中间函数,防止每次建立对象都要new
}
//父类的属性与方法经过prototype传递给中间函数 fn.prototype = Animal.prototype;
//中间函数的实例将父类的属性与方法传递给子类的prototype Ferret.prototype = new fn();

四、扩展子类spa

//为全部Ferret实例定义type属性
Ferret.prototype.type = "domestic";

Ferret.prototype.eat = function(food){

    //子类执行父类的方法
    Animal.prototype.eat.call(this,food);

    //子类的扩展逻辑
    alert(this.type + ' eat ' + food);

}

五、测试继承结果prototype

var animal = new Animal();
var ferret = new Ferret();

animal instanceof Animal
// true
animal instanceof Ferret // false
ferret instanceof Ferret // true
ferret instanceof Animal // true 此处,子类是父类的实例为true,说明继承成功~
ferret.eat('meat');//一、alert(eat meat); 二、alert(domestic eat meat);

 如下是一些啰嗦:code

var a = { a: 'b', c: 'd' };

function a1(){
  this.a = 'b';
  this.c = 'd';
}

a instanceof Object // true
a1 instanceof Object // true

由此能够看出,a与a1均属于对象,那么,有什么区别呢对象

a.prototype == undifiend // true
a1.prototype == undefined // false

typeof a == "object" // true
typeof a1 == "function" // true

Object.keys(a) // ["a", "c"]
Object.keys(a1) // []

a仅仅是一个单纯的key&value,没有构造函数,属于【引用类型】blog

而a1则有prototype,能够实现继承,经过Object.keys()能够看出,a1身为一个Object,不存在key&value,属于【值类型】继承

 

V8中的继承:

function Animal(){}
function Ferret(){}
Ferret.prototype.__proto__ = Animal.prototype// 父类将属性传递给子类
相关文章
相关标签/搜索