javascript - 重写 New()函数。函数里不能含有new()关键字
本文介绍了javascript - 重写 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) {
}
解决方案
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;
}
这篇关于javascript - 重写 New()函数。函数里不能含有new()关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文