Skip to content

Instantly share code, notes, and snippets.

@blanklin030
Last active October 21, 2019 07:57
Show Gist options
  • Save blanklin030/19f464f384647e89a399dc9b3b875866 to your computer and use it in GitHub Desktop.
Save blanklin030/19f464f384647e89a399dc9b3b875866 to your computer and use it in GitHub Desktop.
prototype原型相关

prototype

标识原型,对象通过原型可挂载到类上(继承)

function Obj(param) {
  this.a = param
}
Obj.prototype.print = function() {
  console.log(this.a)
}

const a = new Obj("hello")
a.print() // output: hello

以上可以形成原型链(prototype chain)

proto

proto:将要继承的对象挂载在新对象的某个属性上》

a.__proto__ === Obj.prototype //output true

constructor

《constructor: 一个函数(比如上面的 Obj)的 prototype 有个 constructor 属性,默认(可以改)指向函数本身。》

Obj.prototype.constructor === Obj //output: true

完整原型链

const ele = Document.body;
let result = "";
let parentClass = ele.constructor; //获取父类
let parentProto = parentClass.prototype; //获取父类的原型
while(parentProto) {
  result += "->" + parent.name;
  parentClass = parentClass.constructor; //获取父类
  parentProto = parentClass.prototype; //获取父类的原型
  // 可通过Object.getPrototypeOf(ele)获取父类的原型,等同于ele.constructor.prototype
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment