3

如何将对象从函数传递到它自己的原型函数?

function Main()
{
    this.my_object = {"key":123};
}

Main.prototype.Sub = new Sub(this.my_object);

function Sub(obj)
{
    alert(obj);
}

Main.Sub; //this should alert the object created in Main()

小提琴:http: //jsfiddle.net/GkHc4/

编辑1:

我正在尝试创建一个函数链,每个链接都必须获取前一个对象并添加一些东西。在这一点上,它是一个实验。例如:

Main.Link1.Link2.link3();

//link3 it's a prototype for link2
//link2 it's a prototype for link1
//and so on...

每个链接向初始对象添加一个键

4

3 回答 3

2

存在三个不同的问题:

1)您不使用创建对象new Main(),而是尝试Sub直接从构造函数访问该属性。这行不通。您必须创建一个实例:

var main = new Main();
main.Sub; //<-- now you can access it 

2)您尝试使用 访问该属性my_objectthis但在任何功能之外。那也行不通。this可能会指向窗口对象,该对象没有任何名为my_object. 解决方案可能是编写main.my_object,但这会破坏原型的目的。通常,您会为每个实例放置相同的功能或属性。但是您正试图在其中放置一个对于每个实例都应该不同的属性。因此,看起来您根本不需要访问原型,只需将其定义为常规属性即可:

function Main()
{
    this.my_object = {"key":123};
    this.Sub = new Sub(this.my_object);
}

3) 该行main.Sub不执行任何操作。你只是在请求财产Sub。相反,该函数Sub将在您编写new Sub(...). 所以如果你想通过调用一个函数来提醒一些东西,你必须定义一个函数。Sub例如,您可以在 in或 in 中定义一个警报方法Sub.prototype,然后调用此方法:

function Sub(obj)
{
    this.alert() {
        alert(obj);
    }
}

main.Sub.alert();

更新的小提琴

于 2013-07-25T22:43:50.457 回答
1

I think you're going at it in the wrong way.. you see:

  • The alert is not coming from the last line, it's actually coming from the prototype line, when you do the "new Sub".

Maybe a better approach would be something like:

function Main()
{
    this.my_object = {"key":123};
}

Main.prototype.Sub =  Sub; //You set the prototype, but don't actually execute the function

function Sub(obj)
{
    alert(obj);
}

var m = new Main(); //You need to create a new object of type Main in order for it to have access to the method Sub
m.Sub(m.my_object); //this should alert the object created in new Main()

Does this help?

Edit

Additionally, you could even do something like this for the Sub function:

function Sub() {
   alert(this.my_object);
}

Although that way, you wouldn't be able to use the function by itself.

于 2013-07-25T22:33:19.480 回答
1

我认为也许您正在寻找类似以下的内容:

function Main()
{
    this.my_object = {"key":123};
}

Main.prototype.Sub = function () {
    Sub(this.my_object);
};

function Sub(obj)
{
    alert(obj);
}

var main = new Main();  // main object is created with main.my_object property
main.Sub();  // this will do alert(main.my_object)
于 2013-07-25T22:43:48.430 回答