原型链学习面试

原型链类

创建对象有几种方法

1、字面量对象
var o1 = {name:'1'}
var o11 = new Object({name:'11'})
2、显示构造函数创建
var M = function(){this.name ='o2'}
var o2 = new M();
3.Object.create 方法来创建
var P = {'name':'o3'}
var o3 = Objcet.create(P)

原型、构造函数、实例、原型链 的概念
什么叫实例:

instanceof的原理 new运算符原理
面向对象继承有哪几种
1、借助构造函数实现继承

function Parent1(){
this.name ='Parent1'}
function Child1(){
Parent1.call(this)
this.name = 'child1'
}
缺点父类原型链有方法属性,子类拿不到
console.log(new Child1)

2、原型链实现继承

function Parent2() {
    this.name = 'Parents2'
    this.type = [1,23]
}
function Child2() {
    this.name = 'Child2'
}
// Child2.prototype= new Parent2()
       
    console.log(new Child2)
    var c2 = new Child2
    var c3 = new Child2
    c3.type.push(3)
    
    缺点:修改实例继承父类的属性,都会改变

3、组合继承

 function Parent3() {
        this.name = 'Parents3';
        this.play = [1, 23, 3];
    }
    function Child3() {
        Parent3.call(this)
        this.type = 'child3'
    }
    Child3.prototype = new Parent3()
  var  c3 = new Child3()
   var c4 = new Child3()
    console.log(c3.play);
    console.log(c4.play);
    c3.play.splice(1, 1)
    console.log(c3.play);
    console.log(c4.play);
    
    组合继承的优点就是修改实例的属性,不会改变父类的属性。
    这是实现继承的最通用的方式,这种方法的缺点实例化子类的时候父级的构造函数执行了2次,没有必要执行2次。所以出了优化方法

4、优化方式

function Parent4() {
        this.name = 'Parents4';
        this.play = [1, 23, 3];
    }
    function Child4() {
        Parent3.call(this)
        this.type = 'child4'
    }
    Child4.prototype = Parent4.prototype
   var c5 = new Child4()
 var   c6 = new Child4()
    console.log(c4.play);
    console.log(c5.play);
    c3.play.splice(1, 1)
    console.log(c4.play);
    console.log(c5.play);
首先通过call方法把子类实例拿到父类的属性和方法,然后通过父类的原型赋值给子类,拿到父类原型上的属性和方法,这样就实现了继承了

这种方式还有缺点吗
c5 instanceof Child4 c5 instanceof Parent4 //true
如何区分一个对象由子类实例化,还是父类实例化的
这时候c5.constructor 指向了Parent4构造函数
为什么指向了parent4构造函数而不是指向Child4构造函数呢,因为上边有一句是
Child4.prototype = Parent4.prototype
这时候子类的原型指向了父类的原型,所以子类的实例当然是指向了父类构造函数了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值