2014-09-24 18 views
0

比方說,我定義下面的類在我AngularJs代碼中使用:類在AngularJS - 屬性和方法

app.factory("exampleClass", function() { 
    // constructor 
    function exampleClass(val) { 
     this.prop1 = val; 
     this.result = ""; 
    } 

    // methods 
    exampleClass.prototype = { 
     doSomething: function (userVal) { 
      this.result = this.prop1 + userVal; // any way to avoid this? 
      console.log(this.result); 
     } 
    }; 

    // return class 
    return (exampleClass); 
}); 

// .. later in code 
new exampleClass("another").doSomething("321"); 
console.log(scope.example.prop1); 

有什麼辦法來逃避引用類字段(PROP1和結果)與此有關。在doSomething方法中,仍然可以直接從課外引用它們?很明顯,我試圖在其他現代語言中效仿類似public type fieldName的東西 - 當這個。先不查看實例變量?

回答

1

不幸的是沒有。 JavaScript(至少在瀏覽器支持的當前版本中)不支持方法的自動屬性訪問。

這是理論上可能得到你想要與涉及with()或局部變量和Object.defineProperty掛羊頭賣狗肉的語法,但它最終會使得你的代碼的其餘部分更噁心。

想要獲得更好的JavaScript語法的更可行的方法是將多種語言編譯爲JavaScript。例如,如果CoffeeScript支持使用Ruby類型@foo語法的屬性訪問。