AKG
AKG

Reputation: 3286

Call property of a function from within another function

var Apple = function() {
    this.hello = 'alrightalrightalright';
}

var Banana = function() {
    this.howdy = 'matthew mcconaughhey';
        console.log(a.hello); // returns 'alrightalrightalright';
}

var a = new Apple();
var b = new Banana();

In the code above (which is a simplified form of what I already have), I want to call the hello property of the Apple function from within the Banana function. Obviously I can do this by a.hello from within the Banana function, since a is an instance of Apple. However, this might be error-prone in later stages when you revisit the code.

Is there a way I can reference the hello property of the Apple function from another function without referencing the instance?

Upvotes: 0

Views: 45

Answers (2)

jfriend00
jfriend00

Reputation: 707336

To answer your question literally, no with the way you've coded the Apple object, you cannot access the hello property without an instance of the Apple object.

The hello property only exists on an instance of the Apple object so you must have an instance of that object in order to be able to reference that property as in a.hello.


You can redesign where the hello property is stored such that you can access it with an instance of the Apple object, but that means changing where the property is defined.

For example, it can be made a static variable (which is not a property of any specific Apple object) by defining it like this:

var Apple = function() {

}

Apple.hello = 'alrightalrightalright';

Then, you can reference it like this:

var Banana = function() {
    this.howdy = 'matthew mcconaughhey';
    console.log(Apple.hello); // returns 'alrightalrightalright';
}

var b = new Banana();

But, keep in mind that this changes the behavior of the hello property. It is now not a separate property of each Apple object. Instead it's essentially a single global property on the Apple function object. It only has one value, no matter how many instances of Apple you have and you can reference it inside an Apple object using this.hello because it isn't a property of each Apple object any more. All references to it would need to be Apple.hello.


In the end, you need to decide if this is really supposed to be a property of the Apple object that could possibly have a unique value for each separate Apple object or if this is really just a static variable that you can just define once and reference that one definition from anywhere.

Upvotes: 1

row1
row1

Reputation: 5578

You could make it a static property.

var Apple = function() {
};
Apple.hello = 'alrightalrightalright';

var Banana = function() {
    this.howdy = 'matthew mcconaughhey';
        console.log(Apple.hello); // returns 'alrightalrightalright';
};

Upvotes: 1

Related Questions