0

我正在使用 Aptana Studio 3 编写 Javascript OOP 代码,我正在使用“new”和“this”创建类和对象,但真的很烦人,因为没有 IDE 自动完成功能无法识别我的对象属性和方法。

也许如果我更改为文字表示法,IDE 会识别我的对象并启用自动完成功能,但我无法将我的代码转换为保持相同功能的文字表示法。

我写了一个示例,我通常是如何写的。

var ClassPerson=function(name,lastName){

    //initialize stuff here
    alert(name + ' was just created now!');

    var time=setInterval( function(){getOlder(1);} ,(1000*60*60*24*365));

    //public properties
    this.name=name;
    this.lastName=lastName;

    //private properties
    var age=0;
    var weight=3;

    var parent=this; //reference to 'this' of this object, not the caller object.

    //public methods
    this.speak=function(text){  
        alert(text);
    }

    this.walk=function(steps){
        weight=weight-(0.05*steps);
    }

    this.eat=function(kcal){
        weight=weight+(kcal/2);
    }

    //private methods
    function getOlder(years){
        age=age+years;
    }
}

var me = new ClassPerson('Justin','Victor');
me.speak( me.name );
me.eat(2500);

如果有人可以将其转换为文字,也许我可以弄清楚它是如何工作的。

4

2 回答 2

1

这是一个小例子:

var sample = function (a,b) {
  this.a = a;
  this.b = b;
} 
var sampleObj = new sample(0,1);
sampleObj.a == 0; // true    

var a = 0, b = 1;
var sample = {
    a: a,
    b: b
}
sample.a == 0; // true
于 2011-10-19T16:50:40.487 回答
0

// 在不使用 new 关键字的情况下调用 var johnsmith=ClassPerson('John','Smith') 会有所帮助吗?

function ClassPerson(name, lastName){
    if(!(this instanceOf ClassPerson)) return new Classperson(name, lastName);
    //constructor code
于 2011-10-19T17:45:43.523 回答