[英]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.