在类属性对象内引用父类属性和方法

时间:2010-03-06 19:54:41

标签: javascript oop

我想一劳永逸地解决这个困惑!我无法访问我的一些类属性和方法。现在,我知道我可以使用对象文字并将所有引用附加到对象名称e.i.动物。但我想知道如何用实例化的类来处理它。

以下是我的代码的快速示例..

function animal(){
       this.type = "Reptile";
       this.sayType = function(){
           //from my experiences "this" right here still refers to "animal"
           alert(this.type);
      };
      this.names = {
          name : "Lizard",
          sayTypeAndName : function(){
             //Now "this" refers to "names" not the "sayTypeAndName" method or the parent
             //animal. If I try to refer to "animal" like I would in an object literal 
             //and construct the class. I get an error saying the method below does 
             //not exist. HOW DO I CORRECTLY REFER TO THE PARENT CLASS PROPERTIES?
             //DO I STICK THE PARENT CLASS PROPERTIES AND METHODS INTO MY "names" object?
             animal.sayType(animal.type+" "+this.name);
          }
      };//end of names object
}//end of class

谢谢大家对此的任何帮助

1 个答案:

答案 0 :(得分:2)

function SomeClass() {
    var self = this;
    this.something = {
        foo: function() {
            self; // <= points to instance of SomeClass
        };
    };
}