Skip to content

原型链的应用

基础方法

W3C不推荐直接使用系统成员proto,访问的话推荐使用API。

Object.getPrototypeOf(对象)

获取对象的隐式原型

Object.prototype.isPrototypeOf(对象)

判断当前对象(this)是否在指定对象的原型链上

js
A.isPrototypeOf(B); //A 是不是 B 的原型链上的爸爸 / 爷爷?

对象 instanceof 函数

判断函数的原型是否在对象的原型链上 即 A 是不是 B

js
[] instanceof A;

Object.create(对象)

创建一个新对象,其隐式原型指向指定的对象

js
var A = { name: "A" };
var B = Object.create(A);
console.log(B); //B的__proto__指向了A

Object.prototype.hasOwnProperty(属性名)

判断一个对象自身是否拥有某个属性

js
function Person() {
  this.name = "张三";
}

Person.age = 18;

const p = new Person();

console.log(p.hasOwnProperty("name")); //true
console.log(p.hasOwnProperty("age")); //false

for in 循环会遍历该对象及其原型链上所有的属性

js
for (let key in p) {
  //一般都会做一个判断是否是自身属性
  if (p.hasOwnProperty(key)) {
    console.log(key);
  }
}

应用

类数组转换为真数组

js
Array.prototype.slice.call(类数组);

实现继承

默认情况下,所有构造函数的父类都是Object

圣杯模式

继承

js
//继承的实现
this.myPlugin.inherit = function (son, father) {
  son.prototype = Object.create(father.prototype); //创建一个对象,该对象的隐式原型指向父类的原型对象
  son.prototype.constructor = son; //重写构造函数,指向子类
  son.prototype.super = father.prototype; //圣杯模式 标准
  son.prototype.uber = father; //圣杯模式 袁
};

使用继承:

js
// 父类
function User(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
  this.fullName = this.firstName + " " + this.lastName;
}

User.prototype.sayHello = function () {
  console.log(`大家好,我叫${this.fullName},今年${this.age}岁了`);
};

// 子类
function VIPUser(firstName, lastName, age, money) {
  this.uber(this, firstName, lastName, age); //袁-继承改变子类this指向  这种本质都是给子类的this加上父类上已有的属性和方法
  User.call(this, firstName, lastName, age); //标准-继承改变子类this指向
  this.money = money;
}

myPlugin.inherit(VIPUser, User); //需要先改变继承

VIPUser.prototype.upgrade = function () {
  console.log(`使用了${100}元软妹币,升级了!`);
  this.money -= 100;
};

var vUser = new VIPUser("张", "成", 1, 100);

兼容es5之前的写法-雅虎写法

js
this.myPlugin.inherit = (function () {
  var Temp = function () {};
  return function (son, father) {
    Temp.prototype = father.prototype;
    son.prototype = new Temp();
    son.prototype.constructor = son;
    son.prototype.uber = father.prototype;
  };
})();

MIT License