类在AngularJS - 属性和方法
问题描述:
比方说,我定义下面的类在我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
的东西 - 当这个。先不查看实例变量?
答
不幸的是没有。 JavaScript(至少在浏览器支持的当前版本中)不支持方法的自动属性访问。
这是理论上可能得到你想要与涉及with()
或局部变量和Object.defineProperty
挂羊头卖狗肉的语法,但它最终会使得你的代码的其余部分更恶心。
想要获得更好的JavaScript语法的更可行的方法是将多种语言编译为JavaScript。例如,如果CoffeeScript支持使用Ruby类型@foo
语法的属性访问。