Skip to content

Instantly share code, notes, and snippets.

@SoarLin
Created July 29, 2022 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoarLin/f1d57311fd590d71cce5b8aca488cb46 to your computer and use it in GitHub Desktop.
Save SoarLin/f1d57311fd590d71cce5b8aca488cb46 to your computer and use it in GitHub Desktop.
function inherit(Child, Parent) {
// 繼承原型上的屬性
Child.prototype = Object.create(Parent.prototype);
// 修復 constructor
Child.prototype.constructor = Child;
// 儲存超類別
Child.super = Parent;
// 靜態屬性繼承
if (Object.setPrototypeOf) {
// setPrototypeOf es6
Object.setPrototypeOf(Child, Parent);
} else if (Child.__proto__) {
// __proto__ 在ES6被引用,但已被大多瀏覽器支援
Child.__proto__ = Parent;
} else {
// 舊版本瀏覽器 IE10 以上
// 將 Parent 上靜態屬性和方法 copy 到 Child 上,但是不會覆蓋 Child 上原有的方法
for (var k in Parent) {
if (Parent.hasOwnProerty(k) && !(k in Child)) {
Child[k] = Parent[k];
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment