简体   繁体   中英

Calling object prototype from another object's prototype

Probably obvious, but still confusing me.

Is it in anyway possible to call from an another object's prototype a prototype inside another object?

Current set:

function obj1() {
    this.myVar = 1;
}

obj1.prototype.helloWorld = function() {
    alert("Hello world!");
}

function obj2() {
   this.myVar = 2;
}

obj2.prototype.nonSense = function() {
    console.log(this.myVar);
}

1. Can Obj2 prototype nonSense somehow call the prototype helloWorld in Obj1 ?**
2. Can Obj2 prototype nonSense somehow access the Obj1 variable myVar ?

I'm not really sure what you're trying to do but you can call the helloWorld method directly:

obj1.prototype.helloWorld();

If you have an instance of obj1 , you can get rid of the prototype :

var myObj1 = new obj1();
myObj1.helloWorld();

To access myVar from outside of obj1 you will need to have called obj1 - myVar won't exist until you have called the function in which it is declared. Most likely, you will want to create an instance of obj1 by calling it with the new operator, as shown above. You can then access myVar just like any other property:

console.log(myObj1.myVar);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM