【问题标题】:Convert Javascript 'new object' to literal notation将 Javascript 的“新对象”转换为文字表示法
【发布时间】:2011-10-19 16:45:22
【问题描述】:

我正在使用 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);

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

【问题讨论】:

    标签: javascript oop object aptana object-literal


    【解决方案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
    

    【讨论】:

    • var obj={ method1:function(params){return(params);}, method2:function(params){return(params);} } 仍然正确吗?私有和公共范围如何?谢谢
    • 你没有使用对象表示法获得私有范围,肯定会退缩
    【解决方案2】:

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

    function ClassPerson(name, lastName){
        if(!(this instanceOf ClassPerson)) return new Classperson(name, lastName);
        //constructor code
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 2011-09-17
      • 1970-01-01
      • 2013-02-24
      • 2021-10-01
      相关资源
      最近更新 更多