javascript - AngularJS 中的类 - 字段和方法

标签 javascript 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 和 result)吗?在 doSomething 方法中,同时仍然能够直接从类外部引用它们?显然,我试图在其他现代语言中模拟类似 public type fieldName 的东西 - 当这个。首先查看实例变量中是否不存在?

最佳答案

不幸的是没有。 JavaScript(至少在浏览器支持的当前版本中)不支持方法的自动属性访问。

理论上,可以通过涉及 with() 或局部变量和 Object.defineProperty 的技巧来获得您想要的语法,但它最终会让你的代码的其余部分变得更加丑陋。

为了以更可行的方式获得更好的 JavaScript 语法,有多种语言可以编译为 JavaScript。一个例子,如果 CoffeeScript它支持使用 Ruby 式的 @foo 语法进行属性访问。

关于javascript - AngularJS 中的类 - 字段和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011672/

相关文章:

javascript - 用于匹配包含 ID 的工作表名称并使其可见的 Apps 脚本

javascript - 在 map 上渲染多个元素 google-map-react

javascript - Context Api 状态没有改变

javascript - 型号不变。最后一个中有多个 ng-repeat 和复选框。

javascript - AngularJS 中 $http 的错误处理程序

javascript - 加载后立即使表单无效

javascript - 使用 Node Express JS 在 AngularJS 中重复 ajax 调用

javascript - 输出显示在屏幕上停留时间更长

javascript - 使用 jQuery 计算窗口调整大小时的 div 高度

angularjs - 工厂方法总是在 AngularJs 中返回 undefined