假设我正在定义要在我的 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 和 result)吗?在 doSomething 方法中,同时仍然能够直接从类外部引用它们?显然,我试图在其他现代语言中模拟类似 public type fieldName
的东西 - 当这个。首先查看实例变量中是否不存在?
最佳答案
不幸的是没有。 JavaScript(至少在浏览器支持的当前版本中)不支持方法的自动属性访问。
理论上,可以通过涉及 with()
或局部变量和 Object.defineProperty
的技巧来获得您想要的语法,但它最终会让你的代码的其余部分变得更加丑陋。
为了以更可行的方式获得更好的 JavaScript 语法,有多种语言可以编译为 JavaScript。一个例子,如果 CoffeeScript它支持使用 Ruby 式的 @foo
语法进行属性访问。
关于javascript - AngularJS 中的类 - 字段和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011672/