按变量重新初始化javascript函数对象

时间:2014-07-05 05:23:30

标签: javascript object

这个在PHP中很容易做到,我发现自己会派上用场,但我不相信PHP技巧会起作用。

基本上我想使用从对象内的函数传递的变量,然后使用子元素(由变量定义)重新初始化该对象。

var View = function(){
    var fn = this;

    fn.load = function(name){
        return new name();
    }
}
var view = View.load('titleView');

这是一个非常早期的工作,所以原谅它看起来很奇怪的事实(仍然需要更多地修补这个概念)。但总的来说,它应该大致显示出这个概念。

有没有办法基本上用新函数重新创建当前函数实例?为了在我想到的方面做到这一点,我将需要使用变量而不是传递新对象。这可能吗?我确信它必须以某种形式出现。任何想法/指针?谷歌一直没有让我失望,因为我不确定正确的关键词。

编辑: 还应该展示" titleView"背后的想法。类

var titleView = function(){}

titleView.prototype = new View;

2 个答案:

答案 0 :(得分:1)

我认为最简单的方法是通过某种工厂生产您想要的类型的视图。像这样:

var View = (function() {
    var registry = {};

    return {
        register: function(type, fn) {
            if (typeof registry[type] === 'undefined') {
                registry[type] = fn;
                return true;
            }
            return false;
        },

        load: function(type) {
            return new registry[type]();
        }
    };
})();

var titleView = function() {
    this.name = 'titleView';
};
var subTitleView = function() {
    this.name = 'subTitleView';
}

View.register('titleView', titleView);
View.register('subTitleView', subTitleView);

var view = View.load('titleView');
console.log("Created view type: " + view.name);

view = View.load('subTitleView');
console.log("Created view type: " + view.name);

这将提供以下内容(允许您动态重新创建view变量):

// Created view type: titleView
// Created view type: subTitleView

如果你尝试按照你的例子的方式去做,你必须像这样使用子类:

function Base() {
    this.name = "Base";
    this.load = function(fn) {
        fn.apply(this);
    }
}
function Other() {
    Base.apply(this, arguments);
    this.name = "Other";
}

var view = new Base();
console.log(view);

view.load(Other);
console.log(view);

// => Base { name: "Base", load: function }
// => Base { name: "Other", load: function }

但是,使用此方法,在调用view.load(Other)之后,您的视图仍会保留调用load之前的所有属性/方法(可能不是您想要的)。< / p>

答案 1 :(得分:0)

认为这就是你的要求

var View = function(){
  this.load = function(name){
  return  name;
  }
}
var myView = new View;
var v = myView.load('titleView');
alert(v);
相关问题