首页 > 编程 > JavaScript > 正文

秒懂JavaScript继承和实现方式

2019-11-08 02:20:17
字体:
来源:转载
供稿:网友

1、继承

概念:一个对象可以访问另一个对象上的成员。在javascript,对象与对象之间是通过PRototype属性来实现成员和方法的共享(继承)。

function Animal(name){ this.name = name}Animal.prototype.eat=function(){ console.log(this.name + 'can eat other small animals .')}var animal1 = new Animal('snake')var animal2 = new Animal('tiger')animal1.eat===animal2.eat //true//animal1.eat和animal2.eat都指向 Animal.prototype.eat ,实现方法共享(继承)

2、原型继承的原理

原型:就是函数的prototype属性所引用的对象 原型继承的原理:一个对象能够访问它的proto属性所指向的对象上的成员和方法(当然如果这个对象本身有它要访问的成员和方法,就不去它的proto属性所指向的对象上查找,逐级向上查找,直至null,则返回undefined)

var a = {}//继承关系:a -> Object.prototype ->null// a.hasOwnProperty 就是访问的Object.prototype上的hasOwnProperty方法。因为a本身并没有hasOwnProperty方法,而a.__proto__属性指向 Object.prototype ,且Object.prototype上有hasOwnProperty方法

3、原型链

概念:从一个对象到Object.prototype之间存在一条体现继承层次关系的链式结构。 本质:链上的每一个对象都是通过proto属性连接起来的

...jsvar a = {};//原型链:a -> Object.prototype -> nullvar arr=[];//原型链:arr -> Array.prototype -> Object.prototype -> nullfunction Person(){}var p1 = new Person()//原型链:p1 -> Person.prototype -> Object.prototype -> null...

4、js继承的实现方式

function Person(name,age){ this.name = name this.age = age}Person.prototype.run = function(){ console.log(this.name + 'can run !')}

(1)简单原型继承

var p1 = new Person('Jeck',23) var p2 = new Person('Rose',22) p1.run === p2.run //true // p1 和 p1 都能访问 Person.prototype上的run方法

(2)置换原型继承

Person.prototype = { eat:function(){ console.log(this.name + 'can eat !') }}var p1 = new Person('Jeck',23)var p2 = new Person('Rose',22)p1.eat === p2.eat //true// p1 和 p1 都能访问 Person.prototype上的eat方法

(3)扩充原型式继承

function Child(name.age){ this.name = name this.age = age}//IE8以下不支持Object.create()方法//兼容代码if(!Object.create){ Object.create = function(Person.prototype){ function F(){} F.prototype = Person.prototype return new F() }}Child.prototype = Object.create(Person.prototype)// 相当于 Child.prototype 是Person.prototype 它new出来的var c = new Child('lili',12)//继承的原型链://c -> Child.prototype -> Person.prototype -> Object.prototype -> nullc.run; // 访问的是Person.prototype上的run方法

(4)拷贝式继承

function extend(o1,o2){ for(key in o2){ if(o2.hasOwnProperty(key)){ o1[key]=o2[key] } }}var o1 = {name:'tom',sing:function(){ console.log(this.name +'can sing !')}}var o2 = { name:'lily', jump:function(){ console.log(this.name +'can jump high !') }}extend(o1,o2)o1.jump() // lilycan jump high !而不是tomcan jump high !

(5)对象冒充式继承#

function Child(name,age,gender){ this.parent = Person this.parent(name,age) delete this.parent this.gender = gender } var c = new Child('meimei',20,'femail') console.log(c) //{name:'meimei',age:20,gender:'femail'}

(6)组合继承

function Child(name,age){ Person.call(this,name,age) //或者 Person.apply(this,arguments)}Child.prototype = new Person()var c = new Child('QQ','sweet')c.run();//qq can run !//原型链继承:// c -> Child.prototype -> Person.prototype -> Object -> null
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表