prototype原型链继承

本文深入讲解JavaScript中的继承机制,通过具体实例演示了如何利用原型链实现继承,包括定义父类和子类、实现子类对父类方法的重写与扩展等关键步骤。

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

1、定义父类及父类方法

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

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

2、定义子类

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

}

3、原型链继承核心

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

4、扩展子类

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

Ferret.prototype.eat = function(food){

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

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

}

5、测试继承结果

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');//1、alert(eat meat); 2、alert(domestic eat meat);

 以下是一些啰嗦:

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,没有构造函数,属于【引用类型】

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

 

V8中的继承:

function Animal(){}
function Ferret(){}
Ferret.prototype.__proto__ = Animal.prototype// 父类将属性传递给子类

 

 

转载于:https://www.cnblogs.com/fengxiangks/p/6015812.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值