Javascript 有没有办法从对象';什么方法?
有没有办法从对象的方法中删除对象 让我详细解释一下。我有一个名为“Test”的JS类,我创建了这个类的一个新实例,并将其分配给一个变量,如下所示Javascript 有没有办法从对象';什么方法?,javascript,prototype,prototype-programming,Javascript,Prototype,Prototype Programming,有没有办法从对象的方法中删除对象 让我详细解释一下。我有一个名为“Test”的JS类,我创建了这个类的一个新实例,并将其分配给一个变量,如下所示 var Test = function() { } Test.prototype = { printLog: function() { // Print some values }, destroy: function() { //Here I want to delete
var Test = function()
{
}
Test.prototype =
{
printLog: function()
{
// Print some values
},
destroy: function()
{
//Here I want to delete **this** Test object.
}
}
var a = new Test();
a.destroy();
console.log(a); //It should print null instead on object code.
现在,我想通过调用a.destroy删除在变量a中分配的新创建的测试类对象,如下所示
var Test = function()
{
}
Test.prototype =
{
printLog: function()
{
// Print some values
},
destroy: function()
{
//Here I want to delete **this** Test object.
}
}
var a = new Test();
a.destroy();
console.log(a); //It should print null instead on object code.
调用destroy()方法后,变量a值应在控制台日志中打印为null。为什么不简单地编写
a=null代码>而不是a.destroy()代码>
在销毁方法内部,您不能使用删除此
,因为此
不是属性而是对象。看起来你不能写this=null代码>两者都不是。但是正如我所说的,我并不认为你需要一种方法来使你的对象为空:)你可以使用destroy方法的一种方法是使用一个名称空间,通过硬编码变量名,并将两者作为参数发送给destroy。
但是,这让事情变得更复杂了。因此var a=null
是我的首选解决方案
但是如果您选择destroy()方法,那么最好在名称空间中使用destroy方法,而不是在类的原型中
var Test = function() {
};
Test.prototype = {
printLog: function() {
// Print some values
},
destroy: function( namespace, instanceName ) {
namespace[instanceName] = null;
}
};
var instances = {
'a' : new Test()
};
console.log(instances);
instances.a.destroy( instances, 'a');
console.log(instances);
///////////////////////////
var Test = function() {};
Test.prototype = {
printLog: function() {
// Print some values
}
};
var Namespace = function() {};
Namespace.prototype = {
'add' : function( name, obj ) {
this[name] = obj;
},
'destroy' : function( name ) {
delete this[name];
}
};
var ns = new Namespace();
ns.add( 'a', new Test() );
console.log(ns);
ns.destroy('a');
console.log(ns);
您是否尝试将null
值分配给元素(this=null;
)?也许我说的很愚蠢,但我不知道它是否有效。它不起作用,左手作业无效。EcmaScript 6根本没有指定任何垃圾收集语义,因此也没有类似于“销毁”的东西。资料来源:最简单的方法就是不使用方法,只覆盖变量a,但你不能在a中这么做。如果有帮助的话,我发现了以下两个问题:谢谢你的回答。实际上,我正在创建一个组件(示例java脚本窗口)。当用户关闭一个窗口时,close()方法将被调用,从这里我必须使对象为空。