Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS中的类-字段和方法_Javascript_Angularjs - Fatal编程技术网

Javascript AngularJS中的类-字段和方法

Javascript AngularJS中的类-字段和方法,javascript,angularjs,Javascript,Angularjs,假设我在AngularJs代码中定义了以下类: app.factory("exampleClass", function () { // constructor function exampleClass(val) { this.prop1 = val; this.result = ""; } // methods exampleClass.prototype = { doSomething: functi

假设我在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方法中,仍然能够直接从类外引用它们?很明显,我试图在其他现代语言中模仿类似于
公共类型fieldName
的东西——当这种情况发生时。是否不存在第一个查找实例变量?

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

从理论上讲,通过使用
with()
或局部变量和
Object.defineProperty
,可以获得所需的语法,但最终会使代码的其余部分变得更加丑陋

为了获得更好的JavaScript语法,有多种语言可以编译成JavaScript。一个示例,它支持使用Ruby风格的
@foo
语法访问属性