es5 Object.create、new、繼承

Object.create(obj)能夠這樣自定義
(1)
Object._create=function(obj){
    let o={}
    Object.setPrototypeOf(o,obj)
    return o;
}
複製代碼
(2)
Object._create=function(obj){
    function F(){}
    F.prototype=obj
    return new F();
}
複製代碼
function F(){}var f=new F()new能夠這樣自定義
(1)
function _new(Contructor){
  // 將 arguments 對象轉爲數組
  var args = [].slice.call(arguments);
  // 取出構造函數
  var constructor = args.shift();
  let context={}
  Object.setPrototypeOf(context,constructor.prototype);
  var result = constructor.apply(context, args);
  // 若是返回結果是對象,就直接返回,不然返回 context 對象
  return (typeof result === 'object' && result != null) ? result : context;
}
複製代碼
(2)
function _new(){
   // 將 arguments 對象轉爲數組
  var args = [].slice.call(arguments);
  // 取出構造函數
  var constructor = args.shift();
  // 建立一個空對象,繼承構造函數的 prototype 屬性
  var context = Object.create(constructor.prototype);
  // 執行構造函數
  var result = constructor.apply(context, args);
  // 若是返回結果是對象,就直接返回,不然返回 context 對象
  return (typeof result === 'object' && result != null) ? result : context;
  }
var f=_new(F,1,2)
複製代碼
因此es5構造函數的繼承能夠有多種寫法
function Sub(props){
    Super.call(this);
    this.props=props;
}
複製代碼
(1)
Sub.prototype=Object.create(Super.prototype);
複製代碼
(2)
let o={}
Object.setPrototypeOf({},Super.protype)
Sub.prototype=o;
複製代碼
(3)
function F(){}
F.prototype=Super.prototype;
Sub.prototype=new F();
複製代碼
(4)
Object.setPrototypeOf(Sub.prototype,Super.protype)
複製代碼
最後指定構造函數
Sub.prototype.constructor=Super
複製代碼
繼承要繼承實例方法/屬性和靜態方法/屬性
function A(){
    this.a='a'
}
A.aa='aa'
function B(){
    A.call(this);
    this.b='b'
}
B.bb='bb'
Object.setPrototypeOf(B.prototype,A.prototype);
Object.setPrototypeOf(B,A);
B.prototype.constructor=B;
var b=new B()
console.log(b.a)
console.log(b.b)
console.log(B.aa)
console.log(B.bb)
複製代碼
相關文章
相關標籤/搜索