Javascript - 在类的函数成员中正确使用“this”
Javascript - Correct use of 'this' in a function member of a class
我想在类的函数成员中使用this
对象。该函数可能因类的实例而异。它工作正常,但谷歌闭包编译器向我发送警告,让我觉得我没有正确做。
因此,我的问题:在既不是原型也不是构造函数的函数中使用this
的正确方法是什么?如果没有,我该怎么办而不是尝试在那里使用this
?
以下是我正在尝试做的事情的说明:
/** @constructor */
function MyAlert() {}
/** @type {string} */
MyAlert.prototype.name = "joe";
/** @type {function()} */
MyAlert.prototype.myAlert;
/** @type {MyAlert} */
var formalAlert = new MyAlert();
/** @type {MyAlert} */
var informalAlert = new MyAlert();
informalAlert.myAlert = function() {alert("Hi " + this.name);}
formalAlert.myAlert = function() {alert("Good morning Mr " + this.name);}
formalAlert.myAlert();
informalAlert.myAlert();
编译时,我收到此警告,但找不到解决方法:
JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 11 character 57
formalAlert.myAlert = function() {alert("Good morning" + this.name);}
^
非常感谢您的帮助!
从您的示例中:
formalAlert.myAlert = function() {...}
在 formAlert 上创建一个新的静态属性,该属性隐藏(而不是替换)原型。虽然仍然完全有效的javascript,但重要的是要认识到编译器正确地将这些属性视为不同的属性。
要消除此警告,您只需告诉编译器"this"对象的类型:
formalAlert.myAlert = /** @this {MyAlert} */ function() {...};
相关文章:
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- JavaScript 中的嵌套函数和 “this” 关键字
- React+Meteor:this.ops返回未定义
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- 更新成员数据模型中的记录列表
- jQuery(this).Pparent().Pparente().Prent().find()在iPad上不起作用
- Web应用程序,将成员状态更新为其他成员
- 为什么在这种情况下,“This”确实充当javascript函数中的私有成员
- 成员函数中的Javascript“this”object==“window”
- 在原型中声明 TypeScript 成员,而不是添加到“this”中
- Javascript - 在类的函数成员中正确使用“this”
- 如何使“this”引用成员函数而不是其所有者类的实例
- JS类中没有常量引用"this"用于成员访问
- 成员可见性和'this'javascript对象中的作用域
- 绑定“this"传递对象's成员函数时