如何获取函数内部函数的引用

时间:2015-07-25 20:31:52

标签: javascript

说我有这样的功能

function a() {
 //get a reference
 console.log( /*something that will get me reference to function a*/);
}

为什么吗

我在想我能做到这一点......

function Car() {
   //{reference2myself}.prototype = Vechile.prototype;
   Car.prototype = Vechile.prototype;
}

注意,我要手动设置汽车参考,我不想这样做

另外,顺便说一句,为什么不在主工厂函数中设置原型,我明白它意味着为该函数创建的每个实例都会将所有原型道具重新分配给同一个东西。

我真正想做的是:

Object.prototype.extend = function(clas) {
   clas.call(this);
   this.prototype = this.prototype || {};
   Object.setPrototypeOf(this.prototype, clas.prototype);
   this.prototype.constructor = arguments.caller;
}

//then i could use it like this

function Vechile(){
 this.loc=0;
}

Vechile.prototype.move = function(){
  this.loc++;
};

function Van(){
 this.extend(Vechile);
}
Van.prototype.pickUp = function(){};

var a = new Van();
    // now a should have pickup method
    // move method
    // and Van prototype should be and object which should have its __proto__ set to Car.prototype

更新

我想我终于找到了让我轻松模拟类继承的代码。如果我遗失了什么,请告诉我。

Object.prototype.extends = function(clas) {
   clas.call(this);
   var proto = Object.getPrototypeOf(this);
   Object.setPrototypeOf(proto, clas.prototype);
}

//then i could use it like this
//super class
function Vechile(){
 this.loc=0;
}

Vechile.prototype.move = function(){
  this.loc++;
};

//sub class
function Van(){
  this.extends(Vechile);
}

Van.prototype.pickUp = function(){};

var a = new Van();

1 个答案:

答案 0 :(得分:1)

简答:不要。

Car函数是一个构造函数。因此,它将继承原型属性。您不希望将Car.prototype = whatever 放在构造函数中,而是将放在之外。

function Car() {
    // foo
}
Car.prototype = Vehicle.prototype;

编辑:

如果您打算将Car作为Vehicle的子类:

function Car() {
    Vehicle.call(this);
    // this.parent = Vehicle or whatever you want to do
}
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Vehicle;
相关问题