对象实例化后,构造函数中的JS运行函数 [英] JS run function from constructor after object instantiation
本文介绍了对象实例化后,构造函数中的JS运行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以这样做:
var hammer = new Hammer(); // create a new instance
hammer(nail); // really call Hammer.prototoype.hit(object);
我可以在原始对象上找到它,但是在创建对象的新实例时找不到.这就是我遇到的问题:
I can figure it out on a raw object, but not when creating a new instance of an object. This is what I am running into:
function Hammer(options) {
this.config = options.blah;
this.hit(/* ? */);
return this;
}
Hammer.prototype.hit = function(obj) {
// ...
}
当我调用构造函数时,我想传递特殊的选项-而不是要敲的钉子.但是,稍后再调用时,我想传递一个钉子.我丢失了一些东西.
When I call the constructor, I want to pass in special options - not what nail to hit. However, when I call it later, I want to pass in a nail. I'm missing something.
推荐答案
一种解决方案是根本不创建构造函数:
One solution is to not create a constructor function at all:
var hammer = newHammer();
hammer(nail);
hammer.clean();
function newHammer(options) {
var config = options.blah;
hit.clean = clean;
return hit;
function hit(obj) {
// ...
}
function clean() {
// ...
}
}
对我来说,这是比弄乱构造函数和原型更干净的解决方案.
To me, this is a much cleaner solution than messing around with constructors and prototypes.
这篇关于对象实例化后,构造函数中的JS运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文