简体   繁体   English

获取实例化构造函数的调用对象?

[英]Get the calling object of an instanced constructor?

I'm not sure if the title did this justice, but here is what I have... 我不确定标题是否做到了这一点,但这就是我所拥有的...

function A() {};

A.prototype.B = function(){
   this.backref = //??  --  should be set to "a"
};

var a = new A();  // specialized factory...

var b = new a.B();  // instantiate an "a" specialized version of B
var zztop = b.backref instanceof A; //would be true

I need to assign backref to the instance "a" that called the B constructor. 我需要将backref分配给称为B构造函数的实例“ a”。 How can I do this? 我怎样才能做到这一点? I've looked through all the properties in Chrome debugger, and am not even sure it is possible. 我已经浏览了Chrome调试器中的所有属性,甚至不确定是否可行。 Anyone know how to do this? 有人知道怎么做吗? I need to do this because I need access to variables stored in "a". 我需要执行此操作,因为我需要访问存储在“ a”中的变量。 Or is there a better way to do something similar? 还是有更好的方法来做类似的事情?

I'm not sure if there's a way to do this just using the properties given to you, but you can always make the backref one of the arguments to the B constructor: 我不确定是否仅使用给定的属性就能做到这一点,但是您始终可以使backref成为B构造函数的参数之一:

A.prototype.B = function(backref) {
    this.backref = backref;
}

var a = new A();
var b = new a.B(a);

Ugly, but it works. 丑陋,但是行得通。

What you are describing is called inheritance. 您所描述的称为继承。 You want object B to inherit the properties of object A. 您希望对象B继承对象A的属性。

function A() {
  this.length = 3;
}

function B() {
  this.height = 5;
}

B.prototype = new A();
B.prototype.constructor = B;

var obj = new B();

obj.height;  // returns 5
obj.length;  // returns 3

Here's a jsFiddle: http://jsfiddle.net/d6QeT/ 这是一个jsFiddle: http : //jsfiddle.net/d6QeT/

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

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