Javascript AngularJS中的类-字段和方法
假设我在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
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
语法访问属性