首页 > 重写 New()函数。函数里不能含有new()关键字

重写 New()函数。函数里不能含有new()关键字

创建一个函数nouveau,第一个变量为一个构造函数。比如构造函数Person如下,调用var john = nouveau(Person, 'John', 30) 则返回 my name is john and iam 30.

function Person (name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.introduce = function(){
  return 'My name is ' + this.name + ' and I am ' + this.age;
};

该函数就是完成new的功能。第一个参数为构造函数,其他参数为new时所需参数

function nouveau (Constructor) {   
}


//Object.create 已经有new类似的作用

/**
 * 实例化一个类.
 *
 * @param  {Function(Class)} Constructor  类(构造方法)
 * @param  {Array}           [args]       传入构造函数的参数
 * @return {Object}                       返回类的实例
 */

function nouveau (Constructor, args) {   
  var obj = Object.create(Constructor.prototype);
  Constructor.apply(obj, args||[]);
  obj.constructor = Constructor;
  return obj;
}
//e.g.
var person = nouveau(Person, ['fooName', 18]);

//可以用 instanceof 检查person是否是Person实例
person instanceof Person       

function nouveau(cst) {
    var target = {};
    cst.apply(target, [].slice.call(arguments, 1));
    for (var p in cst.prototype) {
        target[p] = cst.prototype[p];
    };
    target.constructor = cst;
    return target;
}

function nouveau (Constructor) {   
  Constructor(arguments[1],arguments[2]);
  var test = Constructor.prototype.introduce;
  return test();
}
nouveau(Person,'John',30);//"My name is John and I am 30";

抖个机灵。。。



function nouveau(Ctor, args){
    var F = function(){}
    F.prototype = new Ctor(args);
    return new F();
}

============================================

如果是一个new都不出现,那应该就要用一些非标准的API了:


function nouveau(Ctor){
    var args = Array.prototype.slice.call(arguments, 1);
    var tmp = {};
    Ctor.apply(tmp, args);
    tmp.__proto__ = Ctor.prototype;
    return tmp;
}

也可以使用Object.create

【热门文章】
【热门文章】