JavaScript 原型链、继承

对象创建

javascript 中原型我们应该最熟悉,记得刚接触js时候最长说的一句话就是,万事万物皆对象,额那时的我不怎么懂,嗯。。。现在的我感觉说的js里这么说确实有一定的道理,可见js中对象的重要性。好的那么创建对象的方法有以下几种方式吧:

 以上那对象的创建方式:字面量、构造函数、Object.create();

原型链

记得当时项目开发中有个同事问到我的一个问题,你给我讲讲原型链呗,上网搜了张图,这张图我觉得很能诠释所有的关系列表,以及几者之间有联系,基本上很清晰:

// 构造函数 === >> 使用 new 运算符 生成的实例
// 构造函数生成 prototype ===>> 指向原型对象
// 原型对象怎么能知道谁指向的自己 ===>> constructor 通过这个东西指向生成自己的构造函数。
// 实例中的__proto__ 指向的是 ===>> 原型对象
// 那么原型链:就是这样一层层找到最终的Object.prototype的原型对象就是一个链行结构。
// 举个栗子:
const fn = function() {
    this.name="my name is GongXiaoZhu";
}
fn.prototype.say = function() {
    console.log(this.name);
}
var new_fn = new fn();
new_fn.__proto__ ===  fn.prototype // true
fn.prototype.constructor === fn // true

上述栗子足以说明原型、构造函数、实例、原型链之间的关系。所以对于几个方法共同使用到的方法,我们完全可以定义到原型对象上,存储到堆中,我们每个实例化的函数都可以拿到本方法。额,写的最全的继承方式图:如下,这图整懂应该原型链就木有啥东西。

继承

1、借助构造函数实现继承

function Parent1() {
    this.name = "zhangsan"
}
function Child1() {
    Parent1.call(this);// apply
    this.age = 'Child1'
}
var children1 = new Child1();
console.log(children1)

 此种继承方式呐,由于改变的 Parent1 指向,不能继承 Parent1 原型对象上的方法。只能实现部分继承。

2、组合继承方式

function Parent1() {
    this.name = "zhangsan"
    this.arr = [1,2,3]
}
Parent1.prototype = function getName() {
    console.log(this.name);
}
function Child1() {
    Parent1.call(this);
    this.age = 'Child1'
}
Child1.prototype = new Parent1();

var a1 = new Child1();
var a2 = new Child1();
a1.arr.push('4')
console.log(a1,a2)

  

 从这里我们可以实现继承,但是还是有个弊端,Child1.prototype 对象指向的是Parent1.prototype,但是new Parent1() 的 constructor 指向的是 Parent1,所以我们可以直接Object.create(Parent1)这样既可。

function Parent1() {
    this.name = "zhangsan"
    this.arr = [1,2,3]
}
Parent1.prototype = function getName() {
    console.log(this.name);
}

function Child1() {
    Parent1.call(this);
    this.age = 'Child1'
}
Child1.prototype = Object.create(Parent1.prototype);
Child1.prototype.constructor = Child1;

var a1 = new Child1();
var a2 = new Child1();
a1.arr.push('4')
console.log(a1,a2)

这样就可以实现简单的继承,也希望能对您有所帮助,欢迎评论,关注,讨论技术可以关注 掘金 https://juejin.im/user/5cd2a2356fb9a0320c5ac8ad

猜你喜欢

转载自www.cnblogs.com/GongYaLei/p/11965215.html