-1

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?

6
  • 3
    You need to instantiate a View1. For example, var view = new View1(); alert(view.test);. Commented Oct 1, 2013 at 1:45
  • Is there another solution that does not involve instantiating View1? Commented Oct 1, 2013 at 1: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";. Commented Oct 1, 2013 at 2:03
  • @WaleedKhan +1, although you'd also need to call view.function1(). Or perhaps this can be done inside the View1() constructor. Commented Oct 1, 2013 at 2:44
  • developer.mozilla.org/en-US/docs/Web/JavaScript/… Commented Oct 1, 2013 at 2:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this helped me narrow down my problem!
0
View1.prototype.function1.call(View1);

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

Or change View1 to an object.

2 Comments

What if var View1 = function() { }; is being used? I meant as in var View1 = { test: 'Hello' };
I just wanted to clarify that function is an object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.