Is there any way to break a closure easily in JavaScript? The closest I have gotten is this:
var src = 3;
function foo () {
return function () {
return src; }
}
function bar (func) {
var src = 9;
return eval('('+func.toString()+')')(); // This line
}
alert(bar(foo()));
This prints '9', instead of '3', as a closure would dictate. However, this approach seems kind of ugly to me, are there any better ways?
Your code is not breaking the closure, you're just taking the code the makes up a function and evaluating it in a different context (where the identifier src has a different value). It has nothing at all to do with the closure that you've created over the original src.
It is impossible to inspect data that has been captured in a closure. In a sense, such data are even more "private" than private members in Java, C++, C# etc where you can always use reflection or pointer magic to access them anyway.
This could be useful if you are trying to create multiple similar methods in a loop. For example, if you're creating a click handler in a loop that relies on a loop variable to do something a little different in each handler. (I've removed the "eval" because it is unnecessary, and should generally never be used).
// Assign initial value
var src = 3;
// This is the regular js closure. Variables are saved by reference. So, changing the later will
// change the internal value.
var byref = function() {
return src;
}
// To "break" the closure or freeze the external value the external function is create and executed
// immidiatly. It is used like a constructor function which freezes the value of "src".
var byval = function(s) {
return function() { return s };
}(src);
src = 9;
alert("byref: " + byref()); // output: 9
alert("byval: " + byval()); // output: 3
As others said this doesn't seem to be the right thing to do. You should explain why you want this and what you want to achieve.
Anyway, one possible approach could be to access properties of an object inside your function. Example:
var src = 3;
function foo (context) {
context = context || window; // Fall back to the global namespace as default context
return function () {
return context.src;
}
}
function bar (func) {
var context = {src: 9};
return func(context);
}
alert(bar(foo));
If you want to access a variable in a wider scope, just don't reuse the variable name in a narrower scope.
That's how it is supposed to work. Work with it instead of trying to fight it.
Here is the code see if you can understand , closures defined within a loop .
var clicked = false;
for(var i=0;i<temp.length;i++){
(function(index){
if(clicked) return false;
$(temp[index]).on('click',function(){
if($(temp[index]).text()=="" && !$(".cell1").val()){
$(this).text(player1Val);
$(".cell1").val(true);
console.log("first player clicked ");
clicked = true;
$(this).off();
for(var j=0;j<temp.length;j++){
$(temp[j]).off('click');
}
return false;
}
else return false;
});
})(i);
}
Related
In the below code, which one is the right and how these two are different
Using call method
var obj = {
num: 10
};
var add = function(a) {
return this.num + a
}
console.log(add.call(obj,4))
Passing object in parameter
var obj = {
num: 10
};
var add = function(obj,a) {
return obj.num + a
}
console.log(add(obj,4))
Your second code block is just a regular function. The first one however is a bit more tricky. So the question is basically:
When to work with context in javascript?
In javascript, the term context basically means this. It is usually used when you call a method of an object, so that you can refer to the object. That's one of the core concepts of OOP, were we only define a function once inside the prototype, and every object of that class which inherits from it exposes this method, it won't work without context. So that's what this was invented for. However there are some cases, were context is useful without inheritance. E.g. Eventhandlers are usually contextless, as they are not part of any object:
window.addEventListener("load", function(evt){
const el = evt.target;
};
However as it is an Eventhandler of window, wouldn't it make sense that it is executed in the context of window? If you now say "YES", then you (will) probably love JS:
window.addEventListener("load", function(){
this.document.body.innerHTML = "Dynamic context can be cool!";
});
So in JS this is the way of refering to the object, the function refers to. Through Function.prototype.call we can make use of this everywhere. However that does not mean that we should use it everywhere. this should stay in the sense of context, as using it somewhere else will create confusion / uglify your code / make your code buggy.
var add = function(a) {
return this.num + a;
}
In your codesnippet i think its unclear what thisrefers to. So its rather a misuse of this. However it could get a meaning if you make it a method of obj, so its context becomes clear from the code:
const num = {
value:10,
add(a){ return this.value + a }
};
It gets even more beautiful if you use inheritance to make it reusable:
class CustomNumber {
constructor(n = 0){
this.value = n;
}
add(a){ return this.value + a; }
}
const num = new CustomNumber(10);
I want to know how the function has been initialized, with the expression or declaried as fuction. _ Amazon interview question
expression : var a = function (){ }
declaration: function a (){ }
You could just do a.toString() and parse out the name. Or do the same with regular expressions
a.toString().test(/^\s*function\s*\(/);
function a(){ }; // gives false
var a = function (){ }; // gives true
Of course as Grundy pointed out this fails with named functions. Something like
var a = function b() {};
or
function b() {};
var a = b;
And ES6 has .name (see the Browser table at the bottom for the current state of affairs) - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/name
I don't think it's possible to do so. The only difference between:
var func = function(){ };
and:
function func() { };
Is that the first one gets assigned on runtime. The way I see it, is that both function statements return a reference to their respective function objects. In that sense they are both the same. The only thing you could argue is that one is not named and the other one is, but you could have assigned a named function to a variable too.
However, there seems to be a difference on how they get assigned. The second one seems to get assigned to a variable that its named after, right at the start of the execution context. The first one has to wait for the explicit assignment within the execution context.
So you'd be testing for when they get assigned. You might think that's is possible to do so within the global object like:
//some protected vars that can't work without same-origin
var protected = ['caches', 'localStorage', 'sessionStorage', 'frameElement'];
var definedAtInit = [];
for(prop in window){
if(!isSandboxed(prop) && typeof window[prop] === 'function'){
definedAtInit.push(prop);
}
};
function isSandboxed(prop){
return protected.indexOf(prop) !== -1;
}
function isItDefinedAtInit(funcName){
return definedAtInit.indexOf(funcName) !== -1;
}
var func = function() {
console.log('test');
}
var results = { isItDefinedAtInit : isItDefinedAtInit('isItDefinedAtInit'),
func : isItDefinedAtInit('func')
};
document.getElementById('results').innerHTML = JSON.stringify(results, '/t');
<pre id="results"></pre>
However, you could still do something like:
var isItDefinedAtInit = function() { };
//After this, isItDefinedAtInit('isItDefinedAtInit') would be wrong.
And you still have the problems with other execution contexts, I don't think functions declared within a function execution context get attached to any object.
I think these kind of checks are a bad idea to be honest.
There is only way, we can determine function has defined with function declarations not as expression.
as Grundy mentioned name property of the respective function gives require information, if it has been defined with expression name property holds undefined value, else it holds function name.
Here is the code :
var isDefinedAsFunction = function(fn){
return fn.name !== undefined
}
I have done a fair amount of research but have not been able to find any answers, to what seems like a simple question:
I want to associate a property with a function (to use as a static variable in this function), like so:
function foo() {
if (!foo.counter) {
foo.counter = 1;
}
else {
foo.counter++
}
// rest of the function code goes here...
}
If I change the name of the function later, I don't want to have to change references to it inside function definition.
So, is there a way to refer to the currently executing function? (other than arguments.callee which is now deprecated). A keyword like thisFunction?
If not, what is the reason for not having something like this?
I do not know of an identifier or keyword like thisFunction (besides arguments.callee) that JavaScript exposes, but one way to achieve the same effect is to name the function foo in a closure, and return foo from that closure. That way you can always use the name foo within foo to refer to itself, regardless of what variable it's assigned to by your program:
var fn = (function() {
function foo() {
if (!foo.counter) {
foo.counter = 1;
}
else {
foo.counter++
}
// rest of the function code goes here...
}
return foo;
})();
function foo() {
if (typeof foo.counter=="undefined") {
foo.counter = 1;
}
else {
foo.counter++
}
return foo;
}
var x = new foo();
alert(x.counter); //1
var y = new foo();
alert(x.counter); //2
If you don't need to refer to the counter outside of the function, this will work. Instead of setting a variable of the function itself, you define a variable outside of the function and let the function modify that instead. Every time you call makeFoo, it makes a new variable x and returns a function using x. Every time you call the returned function, it still refers to the same x created by makeFoo. Additionally, this entirely encapsulates the variable, ensuring that almost nothing outside of the returned function can change it (it definitely won't be changed by most things outside of the returned function, but there is enough funky javascript reflection that I can't guarantee that nothing will change it). Certainly, moving the function between variables won't affect the counter (ie x=makeFoo();y=x;x=null;).
function makeFoo() {
var x=0;
return function () {
x++;
return x;
}
}
//different counters
x=makeFoo();
y=makeFoo();
x();//returns 1
y();//returns 1
x();//returns 2
y();//returns 2
//same counter
x=makeFoo();
y=x;
x();//returns 1
y();//returns 2
x();//returns 3
y();//returns 4
I'm trying to add some code to every method called on the canvas context. I am trying to do this so I can add each command to an array of commands. This is the code I would think works (but doesn't):
var canvas = Object.getPrototypeOf(document.createElement('canvas').getContext('2d'));
for(p in canvas){
if(canvas.hasOwnProperty(p)){
var original = canvas[p];
canvas[p] = function(){
//extra code to be run
return original.apply(this,arguments);
}
}
}
This seems to me like it should work, but it doesn't. If I use this code in an example, I get a NOT_SUPPORTED_ERR: DOM Exception 9
Demo: http://jsfiddle.net/J3tUD/2/
The problem you're suffering from is the fact that variables aren't block scoped.
When your function runs, it updates the context prototype so that each function calls the same function original, which is the last element owned by the original prototype. In this case, that is webkitGetImageDataHD.
This means when you call ctx.beginPath(); you really call ctx.webkitGetImageDataHD();. This method expects 4 arguments and since it didn't get them it throws the DOM Exception 9.
Since JavaScript doesn't support block scope, you have to force a scope change using a function. Modifying your example, we can create a new function where original is a fixed value:
var context = Object.getPrototypeOf(document.createElement('canvas').getContext('2d'));
function bind(context, p) {
// context, p, and original never change.
var original = context[p];
context[p] = function(){
console.log(p, arguments);
return original.apply(this,arguments);
}
}
// p changes with every iteration.
for(p in context){
if(context.hasOwnProperty(p)){
bind(context, p);
}
}
Find a working demo here: http://jsfiddle.net/bnickel/UG9gF/
JavaScript has no block scope, and you have only one original variable containing the last enumerated function.
This solution won't change the context prototype (a host object!), but only the copies for myContext:
var myContext = someCanvas.getContext('2d');
var CanvasRenderingContext2DPrototype = Object.getPrototypeOf(myContext);
for (var p in CanvasRenderingContext2DPrototype) (function(original, prop) {
myContext[prop] = function() {
// some extra code
original.apply(myContext, arguments);
};
})(CanvasRenderingContext2DPrototype[p], p);
Is there any way to refer to the function object that you're currently executing in? If it's not a method of any object or not called with .call() or .apply(), the this pointer is likely just window, not the function object.
I often use a design pattern like this for global variables that I want scoped to a particular function as this keeps them out of the top level namespace:
function generateRandom() {
if (!generateRandom.prevNums) {
generateRandom.prevNums = {}; // generateRandom.prevNums is a global variable
}
var random;
do {
random = Math.floor((Math.random() * (99999999 - 10000000 + 1)) + 10000000);
} while (generateRandom.prevNums[random])
generateRandom.prevNums[random] = true;
return(random.toString());
}
But, I'd rather not have to spell out the function name every time I want to use a variable scoped to that object. If the name of the function ever changes, there are then a lot of places to change the name.
Is there any way to get the currently executing function object?
Well, you could use arguments.callee()...
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee
From MDN:
Description
callee is a property of the arguments object. It can be used to refer
to the currently executing function inside the function body of that
function. This is for example useful when you don't know the name of
this function, which is for example the case with anonymous functions.
Note: You should avoid using arguments.callee() and just give every
function (expression) a name.
BUT...
What you really want are Javascript Prototypes.
function RandomSomethingGenerator()
{
this.prevNums = {};
}
RandomSomethingGenerator.prototype.generate = function() {
var random;
do {
random = Math.floor((Math.random() * (99999999 - 10000000 + 1)) + 10000000);
} while (this.prevNums[random])
this.prevNums[random] = true;
return(random.toString());
};
Why do I say this?
1.) You're dirtying the global space with all those functions.
2.) Even if you like Jani's suggestion, and you want a "static" function like you have now, my suggestion would be the same, but with a twist: Create your global function, and wrap an instance of an object (built from a prototype) inside the closure and make the call to it (so, basically, make yourself a singleton).
As in this (adapted from Jani's answer):
var randomSomething = (function() {
var randomSomethingGenerator = new RandomSomethingGenerator();
return function() {
randomSomethingGenerator.generate();
};
})();
I don't think there's any way to do exactly what you ask, but you could use a closure for your function-local static variables instead.
You can easily achieve this using an IIFE:
var generateRandom = (function() {
//any function's static variables go here
var prevNums = {};
return function() {
//function code goes here
var random;
do {
random = Math....
}
prevNums[random] = true;
return random.toString();
};
})();
You want arguments.callee. From MDN - callee:
callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is for example useful when you don't know the name of this function, which is for example the case with anonymous functions.
For example:
> foo = function() { console.log(arguments.callee); };
> bar = function() { foo() };
> bar();
function () { console.log(arguments.callee) }
However, I think this is being deprecated. The above link says, "The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode."