使用共享变量创建对象

时间:2012-11-11 04:04:32

标签: javascript oop object

我从来没有涉及过这样的javascript对象,但我认为我有充分的理由。

以下是我的例子:

x = new Something(pallet,['blue','green','orange']);
x.try(['blue']);

我想创建一个设置两个变量pallet和colors数组的对象。

然后在try函数中我想传递一个数组但是在函数中我想要访问pallet和颜色对象。有人能告诉我这是否可能?也许是一个小小的演示或教程?

3 个答案:

答案 0 :(得分:1)

var Something = function( pallet, colors){
    this.try = function(arr){
        //stuff
    }
};

这是一个构造函数,您可以在描述时使用它。尝试可以访问托盘和颜色。正如评论中所提到的,尝试不是一个很好的方法名称,因为它是一个保留字。

答案 1 :(得分:1)

function Something(pallet, colors) {
var myColors = colors;
var myPallet = pallet;

function getColors() {
    for (var i = 0; i < myColors.length; i++) {
        document.write(myColors[i] + "<br />");
    }
}

return {
    getColors: getColors
};
}

var mySomething = new Something('myNewPallet', ['green', 'red', 'blue']);
mySomething.getColors();

好的,我们在这里做的是创建一个闭包,然后将getColors函数返回给实例化Something对象的人。您可以阅读有关闭包herehere的信息。但是,基本上,你正在“关闭”颜色和托盘成员,因为getColors存在于Something()的上下文中,它可以访问所有Something的成员。然后,通过将该函数返回给调用者,我们允许他们使用已“捕获”其托盘和颜色列表的对象调用该功能。

请记住,这是一个非常非常高级别的闭包视图,特别是Revealing Module模式。阅读我在JSFiddle上创建的这个fiddle中包含的链接和猴子。一旦你了解它,我想你会很高兴。

好像你正在尝试制作一个托盘对象,所以我为你创建了一个new fiddle

以下是代码:

function Pallet(palletName, palletColors) {
    this.name = palletName; //name is now a property of Pallet
    this.colors = palletColors; //colors is now a property of Pallet
}

Pallet.prototype.getColor = function(color) {
    //access Pallet properties using the 'this' keyword 
    //ex. this.colors or this.name
    if (this.colors.indexOf(color) > -1) {
        return 'Color found'; //Or whatever you need to do.
    }

    return 'Color not found'; //Or whatever you need to do.
};


var myPallet = new Pallet('myNewPallet', ['green', 'red', 'blue']);
document.write(myPallet.getColor('red'));​ //using document.write for simplicity

答案 2 :(得分:-1)

避免使用new - 根据我的经验,我发现工厂方法更加强大。例如,您可以通过这样做来完成您的要求:

function Something(pallet, colors) {
    var that = {};

    that.foo = function (moreColors) {
        // Here you can access pallet, colors, and moreColors.
        // Use "that" to refer to the current object, not "this".
    };

    return that;
}

x = Something(somePallet, ['blue', 'green', 'orange']);
x.foo(['blue']);