gpt4 book ai didi

javascript - 如何使用 apply 创建一个新的 Backbone View

转载 作者:行者123 更新时间:2023-11-30 18:09:33 25 4
gpt4 key购买 nike

我需要创建一个带有参数数组的新 View 实例。因为我不想打电话

 new View(array)

我试过了 this solution .但不幸的是,这不起作用,这意味着没有 arg 传递给初始化函数。那么是否可以创建一个传入数组的新 View ,但在初始化函数中只使用一次参数?

最佳答案

你可以通过一些原型(prototype)技巧来实现这一点:

function createView() {
var args = arguments;

//create a factory function, so we can get the "this" context
function Factory() { return YourViewClass.apply(this, args);}

//assign factory prototype (essentially makes factory a YourViewClass)
Factory.prototype = YourViewClass.prototype;

//invoke factory function
return new Factory();
};

var view1 = createView({model:model}, 1, 2, 3);
var view2 = createView.apply(null, argumentArray);

用可变参数实例化任何“类”(构造函数)的通用解决方案:

function instantiate(ctor) {
//strip first arg, pass rest as arguments to constructor
var args = Array.prototype.slice.call(arguments, 1);
function Factory() { return ctor.apply(this, args);}
Factory.prototype = ctor.prototype;
return new Factory();
};

//call directly
var view1 = instantiate(YourViewClass, {model:model}, 1, 2, 3);

//partially apply to create a factory for a specific view class
var viewFactory = _.partial(instantiate, YourViewClass);
var view2 = viewFactory({model:model}, 1, 2, 3);

关于javascript - 如何使用 apply 创建一个新的 Backbone View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14954561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com