【学习笔记】js原型链

一.概念

蓝色为原型链

  • 蓝色为原型链
  • 每个实例对象( object )都有一个私有属性(称之为 proto )指向它的构造函数的原型对象(prototype )。该原型对象也有一个自己的原型对象( proto ) ,层层向上直到一个对象的原型对象为 null。根据定义,null 没有原型,并作为这个原型链中的最后一个环节。
  • 几乎所有 JavaScript 中的对象都是位于原型链顶端的 Object 的实例。

二.继承属性

  • 当试图访问一个对象的属性时,它不仅仅在该对象上搜寻,还会搜寻该对象的原型,以及该对象的原型的原型,依次层层向上搜索,直到找到一个名字匹配的属性或到达原型链的末尾。

属性遮蔽(property shadowing)

let Person = function(){
this.name = "梅尔蒂";
this.age = 12;
}

let person = new Person();
Person.prototype.age = 13;
  • 原型链如下:
  • {name:梅尔蒂,age:12}—>{age:13}—>Object.prototype—>null
  • 原型上的age属性不会被访问到,这种情况为属性遮蔽。

三.继承方法

  • 在 JavaScript 里,任何函数都可以添加到对象上作为对象的属性。函数的继承与其他的属性继承没有差别,包括上面的“属性遮蔽”(这种情况相当于其他语言的方法重写)。
  • 当继承的函数被调用时,this 指向的是当前继承的对象,而不是继承的函数所在的原型对象。

四.不同的方法创建的对象和生成的原型链

1.使用语法结构创建的对象

  • var o = {a:1};
  • o —> Object.prototype —> null
  • var a = [“yo”, “whadup”, “?”];
  • a —> Array.prototype —> Object.prototype —> null
  • function f(){
    return 2;
    }
  • f —> Function.prototype —> Object.prototype —> null

2.使用构造器创建的对象

  • 在 JavaScript 中,构造器其实就是一个普通的函数。当使用 new 操作符 来作用这个函数时,它就可以被称为构造方法(构造函数)。
function LuckyStar() {
  this.color = [];
  this.size = [];
}

LuckyStar.prototype = {
addStarColor:function(x){
  this.color.push(x);
}
};

var littleStar = new  LuckyStar();
console.log(littleStar.__proto__ === LuckyStar.prototype);

3.使用class关键字创建的对象

"use strict";

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

class Square extends Polygon {
  constructor(sideLength) {
    super(sideLength, sideLength);
  }
  get area() {
    return this.height * this.width;
  }
  set sideLength(newLength) {
    this.height = newLength;
    this.width = newLength;
  }
}

var square = new Square(2);

4.使用Object.create创建的对象

var a = {a: 1}; 
// a ---> Object.prototype ---> null

var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (继承而来)

var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null

var d = Object.create(null);
// d ---> null
console.log(d.hasOwnProperty); // undefined, 因为d没有继承Object.prototype
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值