var foo = (function(){
var c = function(requests) {
bar();
};
c.prototype = {
bar: bar
};
return c;
})();
var f = new foo();
f.baz(function(){
console.log('new instance of foo created');
});
我想创建一个回调函数,在创建“class”foo
的新实例时调用该函数。这可能吗?显然上面的代码不会编译,我只是想让你知道我想要实现的目标。
答案 0 :(得分:2)
var Foo = function (createdCallback) {
createdCallback();
return this;
};
var bar = new Foo(function () {
console.log("instance created");
});
这是你想要达到的目标吗?
答案 1 :(得分:1)
类似于this?
var foo = (function(){
var c = function(requests) {
// Initialize your instance
// ...
// Notify
notifyCreated(this);
};
c.prototype = { ... };
var createdCallbacks = [];
c.onCreate = function(callback) {
createdCallbacks.push(callback);
}
function notifyCreated(instance) {
// Note: forEach requires ES5 or a shim
// Just use whatever you want to loop over the array
createdCallbacks.forEach(function(callback) {
callback(instance);
});
}
return c;
})();
// Add callback *before* creating instances
foo.onCreate(function(instance){
console.log('new instance of foo created', instance);
});
// Create an instance
var f = new foo();
基本上,您向foo
(以及不到foo.prototype
)添加方法以添加回调。在构造函数中,您将调用所有已注册的回调(此处使用单独的内部函数进行演示)。要使用,您首先注册一个回调,然后开始创建实例。
编辑:根据要求,只需一次回调:
var foo = (function(){
var c = function(requests) {
// Initialize your instance
// ...
// Notify
notifyCreated(this);
};
c.prototype = { ... };
// Use a dummy callback by default
var notifyCreated = function(){};
c.onCreate = function(callback) {
notifyCreated = callback;
}
return c;
})();
编辑2:哎呀,如果你只需要一个回调,你也可以摆脱onCreate
函数并将回调公开为变量。但是有一些缺点:
foo.onCreate(anInstance)
从外部触发回调。如果这些问题没有问题(例如,如果您还没有公开foo
),请随意使用这个非常简单的代码段:
var foo = (function(){
var c = function(requests) {
// Initialize your instance
// ...
// Trigger callback
c.onCreate(this);
};
c.prototype = { ... };
// Expose callback on "class"
c.onCreate = function(){};
return c;
})();
// Set callback *before* creating instances
foo.onCreate = function(instance){
console.log('new instance of foo created', instance);
};
// Create an instance
var f = new foo();
答案 2 :(得分:0)
var foo = function() {
this.baz();
};
foo.prototype.baz = function () {
console.log('new instance of foo created');
};
var f = new foo();