如何在原型函数中删除实例是JavaScript [英] How to have an instance delete itself from within a prototype function is JavaScript

查看:78
本文介绍了如何在原型函数中删除实例是JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个JavaScript构造函数,我在其原型上设置了destroy方法。是否可以从destroy方法中删除(或至少取消设置)实例?这是我正在尝试做的一个例子。

If I have a JavaScript constructor function, and I set a destroy method on its prototype. Is it possible to delete (or at least unset) the instance from the destroy method? Here's an example of what I'm trying to do.

Klass.prototype = {
  init: function() {
    // do stuff
  },
  destroy: function() {
    // delete the instance    
  }
};

k = new Klass
k.destroy()
console.log(k) // I want this to be undefined

我明白我不能简单地用destroy方法做 this = undefined ,但是我以为我可以通过使用这样的超时来解决这个问题:

I understand that I can't simply do this = undefined from with the destroy method, but I thought I could get around that by using a timeout like so:

destroy: function() {
  var self = this;
  setTimeout( function() {
    self = undefined
  }, 0)  
}

我认为超时函数可以从闭包中通过 self 访问实例(但它确实如此),但这似乎不是上班。如果我从该函数内部 console.log(self)它显示为 undefined ,但是 k 仍然是 Klass 的实例。

I thought the timeout function would have access to the instance via self from the closure (and it does), but that doesn't seem to work. If I console.log(self) from inside that function it shows up as undefined, but k in the global scope is still an instance of Klass.

有没有人知道如何使这项工作?

Does anyone know how to make this work?

推荐答案

k 是一个参考指出 Klass 的实例。当您调用销毁作为 Klass的方法 函数内部绑定到您调用 destroy 方法的对象。它现在是对 Klass 的该实例的另一个引用。您在该小闭包中关闭的 self 是对该实例的另一个引用。当您将其设置为 undefined 时,您清除该引用,而不是它背后的实例。你不能真的销毁这个实例本身。您可以忘记关于它(设置所有对 undefined 的引用,你将不会再找到它)但是这就是你可以去的地方。

k is a reference that points out to an instance of Klass. when you call destroy as a method of Klass the this inside the function gets bound to the object you called a destroy method on. It now is another reference to that instance of Klass. The self that you close on in that little closure is yet another reference to that instance. When you set it to undefined you clear that reference, not the instance behind it. You can't really destroy that instance per se. You can forget about it (set all the references to undefined and you won't find it again) but that is as far as you can go.

这就是说,告诉我们你想要实现的目标,我们很乐意帮助你找到解决方案。

That said, tell us what you want to accomplish with this and we'll be glad to help you find a solution.

这篇关于如何在原型函数中删除实例是JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆