0

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?

Julia
  • 151
  • 3
  • 11
  • 3
    You need to instantiate a `View1`. For example, `var view = new View1(); alert(view.test);`. – Waleed Khan Oct 01 '13 at 01:45
  • Is there another solution that does not involve instantiating View1? – Julia Oct 01 '13 at 01:49
  • 1
    You've designed it so that you need to do so, since each instance of `View1` would have its own instance of `test`. You could just have `View1.test = "Hello";`. – Waleed Khan Oct 01 '13 at 02:03
  • @WaleedKhan +1, although you'd also need to call `view.function1()`. Or perhaps this can be done inside the `View1()` constructor. – WynandB Oct 01 '13 at 02:44
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript – Alex W Oct 01 '13 at 02:53
  • I think you were looking for `alert(this.test)` it would make more sense. http://stackoverflow.com/a/16063711/1641941 – HMR Oct 01 '13 at 03:29

2 Answers2

2

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
0
View1.prototype.function1.call(View1);

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

Or change View1 to an object.

WynandB
  • 1,377
  • 15
  • 16