Javascript 在var Foo=(函数(){etc
如果我在类中声明这个Javascript 在var Foo=(函数(){etc,javascript,knockout.js,typescript,Javascript,Knockout.js,Typescript,如果我在类中声明这个 class AlertConfigViewModel { DeleteAlert = function (item) { if (item) { if (confirm('Are you sure you wish to delete this item?')) { this.Alerts.remove(item); } } else {
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(我怀疑您将只有此“类”的一个实例,从而使此关键字的使用过时 使用类似的语法,请尝试以下操作:
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");
}
}
}
如果您需要实例,我会选择另一种语法…为什么不以正常方式将函数声明为类的属性
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()
语法除了作用域问题之外给您带来了什么。请查看此处发布的解决方案:
如果您在构造函数中定义方法体,“this”将始终指向类实例-这是一个技巧,但我认为它是一个非常干净的解决方案。函数中
this
的值取决于调用方式。请说明您对this
的用法有疑问的地方。您似乎缺少)()
在结尾谢谢,但我实际上创建了这个类的一个实例:var viewModel:AlertConfigViewModel=new AlertConfigViewModel(rawJson);因此,我并不想在类级别上工作。我使用的是typescript btwIt本身并不是一个技巧,它利用了创建函数实例时发生的闭包。我已经多次使用它为我的ViewModel对象提供静态DOM操作。