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)
复制代码
相关文章
相关标签/搜索