Javascript 我可以通过修改函数原型在对象构造期间执行操作吗?
我想在构造新对象的同时扩展函数对象以执行更多操作。Javascript 我可以通过修改函数原型在对象构造期间执行操作吗?,javascript,constructor,Javascript,Constructor,我想在构造新对象的同时扩展函数对象以执行更多操作。 有可能吗?无法修改函数原型,以便拦截对函数的调用。最接近这一点的方法是添加一个可以调用的方法来代替构造函数。例如: Function.prototype.create = function() { var obj = new this(); // instantiate the object this.apply(obj, arguments); // call the constructor // do your
有可能吗?无法修改函数原型,以便拦截对函数的调用。最接近这一点的方法是添加一个可以调用的方法来代替构造函数。例如:
Function.prototype.create = function() {
var obj = new this(); // instantiate the object
this.apply(obj, arguments); // call the constructor
// do your stuff here (e.g. add properties or whatever it is you wanted to do)
obj.foo = 'bar';
return obj;
};
function SomeObject(name) {
this.name = name;
}
var obj = SomeObject.create('Bob');
obj.foo; // => 'bar'
或者,您可以编写一个函数,调用该函数来构建构造函数:
Function.makeConstructor = function(fn) {
return function proxyConstructor() {
// check to see if they called the function with the "new" operator
if(this instanceof proxyConstructor) {
var obj = new fn();
fn.apply(obj, arguments);
// do your stuff here (e.g. add properties or whatever it is you wanted to do)
obj.foo = 'bar';
return obj;
} else {
return fn.apply(null, arguments);
}
};
};
var SomeObject = Function.makeConstructor(function(name) {
this.name = name;
});
var obj = SomeObject.create('Bob');
obj.foo; // => 'bar'
您需要提供更多详细信息,否则您的问题将被解决。听起来您希望修改函数原型,以便在任何时候从函数构造对象时都可以执行代码。。。这就是它的要点吗?难道你不能连接一个事件吗?没有任何事件会在你调用对象构造函数时触发。javascript对象模型与浏览器事件模型所在的DOM API不关联。我真的认为这些都是你能得到的。