I have:

View1.prototype.function1 = function() {
    this.test = "Hello";
};

And I want to call test in here:

View2.prototype.funcion2 = function() {
   alert(View1.test);
};

However I get can error that View1 does not exist.

Ideas?

有帮助吗?

解决方案

It's not clear to me what you are trying to do, the following may help (or not).

It's a convention in ECMAScript that variable names starting with a capital letter are constructors, e.g.

function View() {
  ...
}

To add a method to the constructor that is shared by all instances created from it, assign a function to the constructor's prototype:

View.prototype.f1 = function() {
    this.test = "Hello";
};

Now to create an instance:

var view1 = new View();

and call the method:

view1.f1();

This calls View.prototype.f1 and passes view1 as its this value, so a test property is added with a value of "Hello":

alert(view1.test); // Hello

You can't call test since it's value is a string, and a string isn't callable. Only objects that implement the internal [[Call]] method, such as functions or host methods, are callable.

You may be struggling with prototype inheritance. If so, ask here. There are many articles on the web that attempt to explain it, but most are pretty awful.

PS: Firefox doesn't seem to like "function1" as an identifier.

其他提示

View1.prototype.function1.call(View1);

View2.prototype.function2 = function() {
  alert(View1.test);
};

Or change View1 to an object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top