虽然之前有人问过这个问题并且很多人已经回答了,但我的问题严格来说是关于新创建的函数的原型(prototype)。
如果您阅读了这段代码,您就会明白它确实有效。也在这里 codepen .
// main object
var Foo = {};
// main methods
Foo.render = {}; // the Render function to populate later
Foo.start = function(el,ops){
return new Actions(el,ops);
}
// secondary/utility functions
var Actions = function(el,ops){
this.el = document.querySelector(el);
this.ops = ops || {};
this.prepare(); // this builds the Foo.render functions
for (var p in this.ops){
Foo.render[p](this);
}
};
// Action methods
Actions.prototype.prepare = function(){
for (var p in this.ops) {
Foo.render[p] = function(that){ // or r[p]
that.el.style[p] = that.ops[p] + 'px';
}
}
}
// init
var action = new Foo.start('div',{left:15})
// check
console.log(Foo.render['left'].prototype);
<div></div>
问题是新创建的函数 Foo.render['left']
的原型(prototype)是这样的 Foo.render.(anonymous function) {}
诸如 Foo.render.left() {}
之类的东西,我遇到了一些性能损失,因为我无法非常快速地访问新创建的函数的原型(prototype)。
任何人都可以阐明如何调整 .prepare()
函数以在 Foo< 中创建准确/可访问的(我无法选择正确的词)原型(prototype)函数
范围?
谢谢。
最佳答案
您需要在额外的闭包作用域中捕获 p
的值。我还建议避免覆盖已经存在的方法。
Actions.prototype.prepare = function() {
for (var p in this.ops) {
if (!(p in Foo.render)) {
Foo.render[p] = (function(prop) {
return function(that) {
that.el.style[prop] = that.ops[prop] + 'px';
};
}(p));
}
}
};
或
Actions.prototype.prepare = function() {
for (var p in this.ops) {
(function() {
var prop = p;
if (!(prop in Foo.render)) {
Foo.render[prop] = function(that) {
that.el.style[prop] = that.ops[prop] + 'px';
};
}
}());
}
}
关于Javascript:在给定对象问题中动态创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35163206/