How to manually destroy an object in javascript? - javascript

Consider the below code,
function destroyer(obj){
obj = undefined;
}
abcObj = {
a:1,
b:2
}
destroyer(abcObj);
As far as I understand, all I can do is throw the object out of scope and the GC will clean it when it sees fit. But the above code does not throw the object out of scope.
How to force an object out of scope?
Reason for wanting to do so: The thing I wanted to achieve is a class having a static method destroy to destroy the instances of same class. Is that possible in javascript? Or is it that I can't force the cleanup. A cleanup method would be great since, the lib I'm working with spawns a lot of instances like 200 to 300.

You have to modify all the variables pointing to it.
abcObj = null;
You can't use a function to do it because that would copy the value to a new variable and leave the original untouched.
This is probably pointless as you are unlikely to be creating a significant number of objects without them falling out of scope naturally. 99.9% of the time you can just focus on writing code which does what you need it to do and let the JS engine worry about garbage collection in its own time.

Since it's defined globally just destroy it directly :
function destroyer(){
abcObj = undefined;
}
abcObj = {
a:1,
b:2
}
console.log(abcObj);
destroyer();
console.log(abcObj);

There is delete in JavaScript, but it does not delete objects, it deletes properties from objects. For your particular use case it could be used:
function destroyer(name){
delete window[name];
}
test="hello";
console.log(test);
console.log("before destroy");
destroyer('test');
console.log("after destroy");
console.log(test);
It works because you have a global variable, and "global" scope is actually "window" in the browser.
However in the general case the most you could do is to explicitly put your objects into some container object, and then you can remove them from there. It does not worth the effort IMHO.
EDIT: actually it does not work as a code snippet here, because it has its own "global-ish" scope, which is not window. But you can test it in the developer console of a browser.
EDIT2: I was wrong, it works here too, just I got confused because of the lengthy error message. Added log-lines before and after the destroyer-call.

You could pass your variable in an object, as a key, and pass that object to your destroyer function. That way, your function could use the object's first key to retrieve the global variable's name, and then delete it in the window object.
Please note this will only work for global variables.
// retrieves the first key of the object passed as parameter
function getFirstKeyName(someObject){
return Object.keys(someObject)[0];
}
// destroy a global variable by its name
function destroyGlobalVariable(withinAnObject){
// retrieve the variable's name
var globalVarName = getFirstKeyName(withinAnObject);
console.log("Deleting global variable " + globalVarName);
// use delete, assign undefined or null to window[globalVarName];
delete window[globalVarName];
}
abcObj = {
a:1,
b:2
}
// abcObj should be defined :
console.log(abcObj);
// pass your variable name into an object, as a key
destroyGlobalVariable({abcObj});
// abcObj should not be defined now :
console.log(abcObj);

Related

Why doesnt javascript check object's local scope first?

Why doesnt the outer scope get accessed in the inner scope ?
I am coming from C++ world where any reference to an unqualified variable inside a class's method is attempted to be resolved first within the object's scope and then in the outer scope. And this happens without having to use "this" keyword.
For ex:
#include <iostream>
using namespace std;
std::string name = "Global::name";
class MyClass {
private:
string name = "MyClass::name";
public:
void printName() {
// No need to use 'this' keyword to refer to the variables in the
// object's scope, unless there is an ambiguity to resolve
cout << "Name from inside printName is: " << name << "\n";
}
};
int main()
{
MyClass obj;
cout << "Name from inside main is: " << name << "\n";
obj.printName();
return 0;
}
prints
Name from inside main is: Global::name
Name from inside printName is: MyClass::name
But in javascript, the following code snippet
function fn() {
let name1 = "fnB";
console.log("Inside fn() name is : ", name1);
}
var obj = {
name1: "objA",
objFn: function() {
console.log("Inside objFn() name is : ", name1); // ERROR !!
// console.log("Inside objFn() name is : ", this.name1); // OK !
}
}
fn();
obj.objFn();
results in
Uncaught ReferenceError: name1 is not defined
at Object.objFn (my.js:10)
What is the reason javascript doesnt want to refer to the "name1" variable in the scope of "obj" object, without requiring "this" keyword to refer to it ? What is the problem that is being solved by forcing the use of "this" keyword in this context ?
Every language is different and makes different tradeoffs. An obvious difference between C++ and JavaScript wrt class/object methods:
In JavaScript, every function is a standalone object. It doesn't strongly belong to anything.
In C++, class methods belongs the class. They cannot be invoked without it.
In JavaScript, every function is a closure, i.e. it has access to free variables defined in a "higher" lexical scope.
In C++, methods are not closures.
Why does this matter? Consider the following example:
var name = 42;
var obj = {
name: "objA",
objFn: function() {
console.log("Inside objFn() name is : ", name);
}
}
Which name should objFn access according to your expectation?
As it is now, the function would log 42, because that's how lexical scoping + closures work. In order to access the object's name property I have to write this.name.
Now lets assume it was the other way round, that object properties would be accessed before the outer scope. Then in order to explicitly access the outer scope's variables, i.e. 42, we would need some new API, e.g. getVariableFromScope('name'). This is worse than always requiring this for a simple reason: It makes it more difficult to reason about the code. By always requiring this, the rules are very simply:
Want to access a property on the object? this.<property>
Want to access a variable in scope? <variable>
In your case it would be:
Want to access a variable in scope? <variable>, but only if the object doesn't have a property with the same name, otherwise getVariableFromScope('<variable>').
Want to access a property on the object? <property>, but only if there is not a local variable with the same name, otherwise this.<property>.
One possible tradeoff here is consistency vs convenience.
Also consider the following example:
var foo = 42;
function bar() {
console.log(foo);
}
Calling bar() will log 42. Now lets assume I pass the function to some third-party code someOtherFunction(foo) which does:
function someOtherFunction(func) {
var obj = createObject();
obj.func = func;
obj.func();
}
Do you see the problem? The result of calling bar now depends on whether obj has a name property or not. To resolve this, either someOtherFunction needs to know which free variables bar contains or bar needs to know that someOtherFunction assigns it to some object and has to account for that. Either way, the code would be tightly coupled.
Doing what C++ or Java does would basically mean to introduce dynamic scope, and I assume there is a reason why very few languages use it.
(Someone might argue that this is also like dynamic scope. Well, this is a single keyword. It's easier to reason about that than to reason about the space of all possible variable names that could be overwritten.)
There are probably more reason why the behavior you are describing is not desirable in JavaScript. But again, programming language design is all about tradeoffs.
The this keyword behaves quite differently in javascript from how it does in many other languages. The value of this is not figured out until the function is invoked, and may not have anything to do with the object you think its associated with.
For example, consider the following code:
const obj = {
name: 'bob',
sayName: function () {
console.log(this.name);
}
}
const verbalize = obj.sayName; // Make another way to reference the function
console.log(verbalize === obj.sayName); // They're literally the same function
// And yet they log very different things
obj.sayName(); // logs 'bob'
verbalize(); // for me, it logs 1d7dcb5e-0fde-4726-8875-4bdcd636c6eb
Why does verbalize produce such a weird result? Well, since i'm invoking the function without specifying what this should be equal to, this defaults to the global window object, and so i end up logging window.name, which for me happens to be "1d7dcb5e-0fde-4726-8875-4bdcd636c6eb".
So if the language was set up to check this before checking other scopes, the actual result would be (in some cases) to check for global variables before local variables, which is the exact opposite of what we'd like to happen. Thus, this has to be done explicitly.
(ps: while this can be set to the window object in some cases, it can also be set to undefined if you're in strict mode)

Can you get the property name through which a function was called?

I've done a lot of searching and some playing around, and I'm pretty sure the answer to this question is no, but I'm hoping a JavaScript expert might have a trick up his sleeve that can do this.
A JavaScript function can be referenced by multiple properties, even on completely different objects, so there's no such thing as the object or property that holds the function. But any time you actually call a function, you must have done so via a single object (at the very least, the window object for global function calls) and property on that object.
(A function can also be called via a function-local variable, but we can consider the function-local variable to be a property of the activation object of the scope, so that case is not an exception to this rule.)
My question is, is there a way to get that property name that was used to call the function, from inside the function body? I don't want to pass in the property name as an argument, or closure around a variable in an enclosing scope, or store the name as a separate property on the object that holds the function reference and have the function access that name property on the this object.
Here's an example of what I want to do:
var callName1 = function() { var callName = /* some magic */; alert(callName); };
var obj1 = {'callName2':callName1, 'callName3':callName1 };
var obj2 = {'callName4':callName1, 'callName5':callName1 };
callName1(); // should alert 'callName1'
obj1.callName2(); // should alert 'callName2'
obj1.callName3(); // should alert 'callName3'
obj2.callName4(); // should alert 'callName4'
obj2.callName5(); // should alert 'callName5'
From my searching, it looks like the closest you can get to the above is arguments.callee.name, but that won't work, because that only returns the name that was fixed to the function object when it was defined, and only if it was defined as a named function (which the function in my example is not).
I also considered that maybe you could iterate over all properties of the this object and test for equality with arguments.callee to find the property whose value is a reference to the function itself, but that won't work either (in the general case), because there could be multiple references to the function in the object's own (or inherited) property set, as in my example. (Also, that seems like it would be kind of an inefficient solution.)
Can this be done?
Short answer:
No, you cannot get "the property name" used to call your function.
There may be no name at all, or multiple names across different scopes, so "the property name" is pretty ill defined.
arguments.callee is deprecated and should not be used.
There exists no solution that does not use arguments or closure.
Long answer:
As thefourtheye commented, you should rethink what you are trying to do and ask that instead in a new question. But there are some common misconceptions, so I will try to explain why you cannot get the "simple property name".
The reason is because it is not simple.
Before we go ahead, let us clarify something. Activation Objects are not objects at all.
The ECMAScript 5.1 specification calls them Environment Records (10.2.1), but a more common term is Scope chain.
In a browser the global scope is (often) the window object, but all other scopes are not objects.
There may be an object that you use to call a function, and when you call a function you must be in some scope.
With few exceptions, scopes are not objects, and objects are not scopes.
Then, there are many names.
When you call a function, you need to reference it, such as through an object property. This reference may have a name.
Scope chain has declarations, which always have a name.
A Function (the real function, not reference) may also have a function name - your arguments.callee.name - which is fixed at declaration.
Not only are they different names, they are not (always) the "the property name" you are seeking.
var obj = { prop : function f(){} }, func = obj.prop;
// "obj" and "func" are declarations.
// Function name is "f" - use this name instead of arguments.callee
// Property name is "prop"
func(); // Reference name is "func"
obj.prop(); // Reference names are "obj" and "prop"
// But they are the same function!
// P.S. "this" in f is undefined (strict mode) or window (non-strict)
So, a function reference may comes from a binding (e.g. function declaration), an Object (arguments.callee), or a variable.
They are all References (8.7). And reference does have a name (so to speak).
The catch is, a function reference does not always come from an object or the scope chain, and its name is not always defined.
For example a common closure technique:
(function(i){ /* what is my name? */ })(i)
Even if the reference does have a name, a function call (11.2.3) does not pass the reference or its name to the function in any way.
Which keeps the JavaScript engine sane. Consider this example:
eval("(new Function('return function a(){}'))()")() // Calls function 'a'.
The final function call refers the eval function, which refers the result of a new global scope (in strict mode, anyway), which refers a function call statement, which refers a group, which refers an anonymous Function object, and which contains code that expresses and returns a function called 'a'.
If you want to get the "property name" from within a, which one should it get? "eval"? "Function"? "anonymous"? "a"? All of them?
Before you answer, consider complications such as function access across iframes, which has different globals as well as cross origin restriction, or interaction with native functions (Function.prototype.bind for example), and you will see how it quickly becomes hell.
This is also why arguments.caller, __caller__, and other similar techniques are now all deprecated.
The "property name" of a function is even more ill defined than the caller, almost unrealistic.
At least caller is always an execution context (not necessary a function).
So, not knowing what your real problem is, the best bet of getting the "property name" is using closure.
there is no reflection, but you can use function behavior to make adding your own fairly painless, and without resorting to try/catch, arguments.callee, Function.caller, or other strongly frowned-upon behavior, just wasteful looping:
// returning a function from inside a function always creates a new, unique function we can self-identify later:
function callName() {
return function callMe(){
for(var it in this) if(this[it]===callMe) return alert(it);
}
};
//the one ugly about this is the extra "()" at the end:
var obj1 = {'callName2':callName(), 'callName3':callName() };
var obj2 = {'callName4':callName(), 'callName5':callName() };
//test out the tattle-tale function:
obj1.callName2(); // alerts 'callName2'
obj2.callName5(); // alerts 'callName5'
if you REALLY want to make it look like an assignment and avoid the execution parens each time in the object literal, you can do this hacky routine to create an invoking alias:
function callName() {
return function callMe(){
for(var it in this) if(this[it]===callMe) return alert(it);
}
};
//make an alias to execute a function each time it's used :
Object.defineProperty(window, 'callNamer', {get: function(){ return callName() }});
//use the alias to assign a tattle-tale function (look ma, no parens!):
var obj1 = {'callName2': callNamer, 'callName3': callNamer };
var obj2 = {'callName4': callNamer, 'callName5': callNamer };
//try it out:
obj1.callName2(); // alerts 'callName2'
obj2.callName5(); // alerts 'callName5'
all that aside, you can probably accomplish what you need to do without all the looping required by this approach.
Advantages:
works on globals or object properties
requires no repetitive key/name passing
uses no proprietary or deprecated features
does not use arguments or closure
surrounding code executes faster (optimized) than
a try/catch version
is not confused by repeated uses
can handle new and deleted (renamed) properties
Caveats:
doesn't work on private vars, which have no property name
partially loops owner object each access
slower computation than a memorized property or code-time repetition
won't survive call/bind/apply
wont survive a setTimeout without bind() or a wrapper function
cannot easily be cloned
honestly, i think all the ways of accomplishing this task are "less than ideal", to be polite, and i would recommend you just bite the coding bullet and pass extra key names, or automate that by using a method to add properties to a blank object instead of coding it all in an object literal.
Yes.
Sort Of.
It depends on the browser. (Chrome=OK, Firefox=Nope)
You can use a factory to create the function, and a call stack parsing hack that will probably get me arrested.
This solution works in my version of Chrome on Windows 7, but the approach could be adapted to other browsers (if they support stack and show the property name in the call stack like Chrome does). I would not recommend doing this in production code as it is a pretty brittle hack; instead improve the architecture of your program so that you do not need to rely on knowing the name of the calling property. You didn't post details about your problem domain so this is just a fun little thought experiment; to wit:
JSFiddle demo: http://jsfiddle.net/tv9m36fr/
Runnable snippet: (scroll down and click Run code snippet)
function getCallerName(ex) {
// parse the call stack to find name of caller; assumes called from object property
// todo: replace with regex (left as exercise for the reader)
// this works in chrome on win7. other browsers may format differently(?) but not tested.
// easy enough to extend this concept to be browser-specific if rules are known.
// this is only for educational purposes; I would not do this in production code.
var stack = ex.stack.toString();
var idx = stack.indexOf('\n');
var lines = ex.stack.substring(idx + 1);
var objectSentinel = 'Object.';
idx = lines.indexOf(objectSentinel);
var line = lines.substring(idx + objectSentinel.length);
idx = line.indexOf(' ');
var callerName = line.substring(0, idx);
return callerName;
}
var Factory = {
getFunction: function () {
return function () {
var callName = "";
try {
throw up; // you don't *have* to throw to get stack trace, but it's more fun!
} catch (ex) {
callName = getCallerName(ex);
}
alert(callName);
};
}
}
var obj1 = {
'callName2': Factory.getFunction(),
'callName3': Factory.getFunction()
};
var obj2 = {
'callName4': Factory.getFunction(),
'callName5': Factory.getFunction()
};
obj1.callName2(); // should alert 'callName2'
obj1.callName3(); // should alert 'callName3'
obj2.callName4(); // should alert 'callName4'
obj2.callName5(); // should alert 'callName5'

Is "this" necessary in javascript apart from variable definition

My question is dead simple.
I just casually discovered that once you have defined a property with this. into an object, you don't need to prepend this. anymore when you want to call them.
So this. is really meant to be used ad definition time, like var?
I found it my self shortly after, i was referencing the window object with this. since i called my object without using new, so like it was a function.
One extra question, maybe for comments. Inside the main object, if i create a new object, and use this during the object definition, this this what will be referring to?
No, unless the context of this is a global object, such as window. Take the following example:
function Foo(bar) {
this.data = bar;
console.log(this.data); // OK
console.log(data); // ReferenceError
}
In this example, you'll get a ReferenceError: data is not defined on the first console.log(data), unless, data is a global variable. To access the instance's public member, you have to use this.data.
References:
Understanding JavaScript’s this keyword
The this keyword
There are all sorts of circumstances where you MUST use this in order to reference the right data.
These two implementations do very different things:
Array.prototype.truncate(newLen) {
// sets the length property on the current Array object
this.length = newLen;
}
Array.prototype.truncate(newLen) {
// sets a global variable named length
length = newLen;
}
var arr = [1,2,3,4,5,6,7];
arr.truncate(2);
You MUST use this in order to control what happens if you want to modify the current object. Your assumption that you can leave it off and it will still modify the current object's properties is not correct. If you leave it off, you are modifying global variables, not member properties.
So this. is really meant to be used ad definition time, like var?
No, the point of this is to be the current scope of execution. You can (and will) run into weird errors if you don't use this. For example, imagine you are an object with a property val and then on the prototype of that object you have
App.obj = function(){
this.val = 'initial';
}
obj.prototype.myMethod = function(val) {
// how would you assign argument val to object val?
}
also note that your reasoning breaks down with methods.
obj.prototype.meth2 = function(){
myMethod(); // fails where this.myMethod() would work.
}
See http://jsfiddle.net/BRsqH/:
function f(){
this.public='hello!';
var hidden='TOP SECRET!';
}
var instance=new f();
alert('Public data: '+instance.public+ /* gives "hello!" */
'\nHidden data: '+instance.hidden /* gives undefined */
);
Variables created with var are hidden and cannot be viewed nor modified outside the function which created them.
But variables created with this are public, so you can access them outside the function.
I think I got it.
I defined my object as function My_Object(){...} and then called it with MyObject(). This way the My_Object was treated as a function, not an object and therefore this == window.
So in the end I was attaching properties and methods to window instead of My_Object! That's way there were available without prepending .this.
The right way to initialize My_Object as an object is to call it like this new My_Object, isn't right?

Replace a global variable temporarily in a local scope

Before actually asking anything, I'll go ahead and say this is a theoretical question; however, it might be implemented on a website later on.
Anyway, I have a variable, any variable. Let's say it's a and its scope is global. Now, for a specific function, I want to set that variable's value to something other than it's global value, but based on it, and without changing its value globally. For example:
a = {something: "Safe", other: "Foo"}
function hello(){
var a = a.other; // Foo
a.something; // Undefined
}
a.something; // Safe
a.other; // Foo
The issue with the above code is that when I define var a in the function, it will have already cleared the value of the global a locally before setting it; in other words, it would return something like Can't access property [other] of undefined [a].
Again, a should still be a (so using another variable name is not an option, or at least not the ideal one). In fact, the global a should not be accessible from the function hello.
Edit: window will also be overwritten with null, regarding Milan Jaric's answer.
Thanks in advance!
Every global can be accessed using window object, with a little changing your code here is example
a = {something: "Safe", other: "Foo"}
function hello(){
var a = window.a.other; // Foo
console.log(window.a.something); // Safe
}
a.something; // Safe
a.other; // Foo
hello();
or
a = {something: "Safe", other: "Foo"}
function hello(){
var a = this.a.other; // Foo
delete a;
console.log(this.a.something); // Safe
}
a.something; // Safe
a.other; // Foo
hello();
This is what I was looking for...now, before you think I had the answer before I asked, I didn't, I was only able to reach a tangible solution based on Milan Jaric's answer (thanks btw).
a = {something: "Safe", other: "Foo"}
function hello(b){
var window = null;
var a = b; // a.other;
a.something; // Undefined
}
a.something // Safe
a.other // Foo
hello(a.other)
(I never really said what could or couldn't go outside the function).
Let's say it's a and its scope is global.
You mean "a is a global variable".
... for a specific function, I want to set that variable's value to
something other than it's global value, but based on it, and without
changing its value globally.
Impossible. You can create a variable with the same name that is on a scope chain, however you can't conditionally create properties of variable objects (i.e. the objects used for identifier resolution on the scope chain). You can only declare local varaibles, which means they exist before any code is run and so can't be conditional, or you can assign directly to an undeclared identifier at which point it becomes a global variable.
[snipped code]
The issue with the above code is that when I define var a in the
function, it will have already cleared the value of the global a
locally before setting it;
The code doesn't in any way "clear" the value of a. It creates a local variable a so that the identifier a will resolve to that variable, not to the global a. To differentiate betweent the two, you can access the global a as a property of the global object:
var a = 'whatever';
var myFunction = (function(global) {
return function() {
var a; // local a
global.a; // global a
}
}(this));
Again, a should still be a (so using another variable name is not an
option, or at least not the ideal one). In fact, the global a should
not be accessible from the function hello.
Impossible, though it might be almost possible in ES5 strict mode provided the code attempting to access the global a is inside another function and can't get a reference to the global object.
But I don't think you can guarantee that.

Can an object automatically delete itself in javascript once it has achieved its purpose?

I am wondering if it is possible for an object in javascript to delete itself once it has finished its task.
For example, I have the following object...
var myObject = Object.create(baseObject);
myObject.init = function() {
/* do some stuff... */
delete this;
};
myObject.init();
Does this work? If not, is there another way?
That wouldn't work, first because the this value associated with an execution context is immutable.
You might now think that deleting myObject (by delete myObject;) might work, but that wouldn't do it either.
Variables are really properties of the Variable Object, this object is not accessible by code, it is just in front of in the scope chain, where you do the variable declarations.
The Variable statement, creates those properties with the { DontDelete } attribute, and that causes the delete operator to fail.
An option if you want to achieve this is to nullify your myObject instance, but that doesn't guarantees that another reference is still pointing to that object.
Recommended lectures:
Understanding delete
Variable instantiation
No. this is just a local reference to the object so deleting it does not make the object not exist. There is no way for an object to self destruct in this manner. If you have large objects that you believe should be erased afterwards then you should look at using the Facade or Strategy patterns.
You could try
window.namespace.myObject = Object.create(baseObject);
namespace.myObject.init = function() {
/* do some stuff... */
delete window.namespace.myObject;
}
namespace.myObject.init();

Categories

Resources