简体   繁体   English

从另一个对象的原型调用对象原型

[英]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 ?** 1. Obj2原型nonSense某种方式在Obj1调用原型helloWorld吗?**
2. Can Obj2 prototype nonSense somehow access the Obj1 variable myVar ? 2. Obj2原型nonSense可以Obj2某种方式访问Obj1变量myVar吗?

I'm not really sure what you're trying to do but you can call the helloWorld method directly: 我不确定自己要做什么,但是可以直接调用helloWorld方法:

obj1.prototype.helloWorld();

If you have an instance of obj1 , you can get rid of the prototype : 如果您有obj1实例 ,则可以摆脱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. 要从obj1外部访问myVar ,您需要先调用obj1 - myVar在调用声明它的函数之前将不存在。 Most likely, you will want to create an instance of obj1 by calling it with the new operator, as shown above. 如上所示,您很可能希望通过用new运算符调用obj1的实例来创建它。 You can then access myVar just like any other property: 然后,您可以像访问其他任何属性一样访问myVar

console.log(myObj1.myVar);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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