在var Foo = (function(){等中的上下文
Context of this in a var Foo = (function () { etc
如果我在一个类中声明这个
class AlertConfigViewModel {
DeleteAlert = function (item) {
if (item) {
if (confirm('Are you sure you wish to delete this item?')) {
this.Alerts.remove(item);
}
}
else {
alert("something is wrong");
}
};
}
结尾是这样的:
var AlertConfigViewModel = (function () {
function AlertConfigViewModel(json) {
this.DeleteAlert = function (item) {
if(item) {
if(confirm('Are you sure you wish to delete this item?')) {
this.Alerts.remove(item);
}
} else {
alert("something is wrong");
}
};
}
}
如果我在AlertConfigViewModel的上下文中调用AlertConfigViewModel,那么"this"不是AlertConfigViewModel,我认为它会因为它的内部函数AlertConfigViewModel(
为什么不以正常的方式将函数声明为类的属性呢?
class AlertTest {
private alerts:string = "these-alerts";
TraceAlert():void{
console.log(this.alerts); // Logs "these-alerts", wherever it's called from
};
}
class CallTest {
private alerts:string = "not-these-alerts";
constructor() {
var target = new AlertTest (); // Creates an instance of your class, as you say.
target.TraceAlert()
}
}
var t:CallTest = new CallTest();
// Output: "these-alerts"
我不确定FuncName = function()
语法给了你什么,除了范围问题。
请看这里发布的解决方案:TypeScript和Knockout绑定到'this'问题-需要lambda函数吗?
"this"总是指向类实例,如果你在构造函数中定义方法体——这是一个技巧,但在我看来这是一个相当干净的解决方案。
我怀疑你将只有一个这个'类'的实例,使得这个关键字的使用变得过时。
用类似的语法试试:
ClassName = {
Alerts: someObject,
DeleteAlert: function (item) {
if (item) {
if (confirm('Are you sure you wish to delete this item?')) {
ClassName.Alerts.remove(item);
}
} else {
alert("something is wrong");
}
}
}
如果你想要实例,我会使用另一种语法
相关文章:
- 将函数的上下文应用于javascript变量
- 直接在函数声明上使用function.prototype.bind
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- jQuery:.click(function(){(element),collapse('show',f
- 使用JQuery的动态上下文菜单
- 如何访问UIWebView'的子窗口上下文
- 如果连接类型为none,则Javascript Function Only警报
- JQuery在单击正文时隐藏上下文菜单
- JQuery上下文菜单显示/隐藏问题
- 如何从HTTP上下文对象中获取Post数据
- HTML字符串作为上下文
- onLoad function phonegap android
- 为什么我的上下文选择器和.buttonset()在ie中花费了这么长时间
- 丢失对象“;这个“;方法中的上下文
- 防止在移动Safari(iPad/iPhone)中长按/长按默认上下文菜单
- d3防止在上下文菜单上触发mouseout
- reducers在redux中得到Function not Object,what'it’他错了
- 是否可以在不更改上下文的情况下调用函数.apply
- 在没有上下文参数的情况下调用本机绑定函数(function.prototype.bind)
- 在var Foo = (function(){等中的上下文