Why calling a function through bracket notation [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've the following code:
function hi(){
alert("hi");
}
window["hi"]();
I thought the hi will be executed. Is there anything similar, that I could do? (no eval please)
Edit:
I want it in bracket notation as the function names will be in string.

If it doesn't work, you're probably in the wrong scope, try
window.hi = function(){
alert("hi");
}
window["hi"]();
EDIT:
If testing in jsFiddle, the default option of onLoad, or the onDomReady option inserts an event handler that waits for DOM ready with a callback.
The callback function creates a new scope, so when adding properties to the window object you have to reference it specifically with window.prop, just typing prop is not enough as it's not in the right scope.

You can just call it directly:
hi();
Or
window.hi();
if you really want to involve the global object.
edit if you want to access the function by a dynamic name, then you certainly can, but the function must be accessible as a property of some object. The global object is one possibility:
function hi() {
alert("hi");
}
window.hi = hi;
Then window["hi"]() will work. Alternatively, you can create an object for the purpose:
var functionRegistry = {}
function hi() {
alert("hi");
}
functionRegistry.hi = hi;
Then functionRegistry["hi"]() will work.

Related

What is "this.return" in JavaScript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
While in VS Code, I hit the tab after typing return and the VS Code Intellisense auto-completed "return" to "this.return".
I've never seen this before and cannot find any documentation on it.
Does anybody know if this is actually a thing, or if VS Code possibly lost it's marbles.
Note: the object I was working in does not have any properties or functions called "return".
Well, an object could have a property called return:
const obj = {
return: () => { console.log('↩️'); }
};
obj.return();
Were you in the context of a class that had a return property, or maybe its superclass did?
(Honestly it seems more likely VS Code was just being weird.)
You can run console.log("this", this) in most modern browsers this will return the JSON data of this (the variable this refers to the current instance of declared object FYI), and console.log(typeof(this.return)) and it will likely return function (if you get undefined just change it from this.return to return;)
Likely the object either has a property called return that is a function, or something has gone wrong in the autocomplete.

When passing a JavaScript function as a parameter in another function, is it possible to access the other variables passed? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a JavaScript function like this:
obj.use('hello', function () {
// Here I want to access the string 'hello'
});
Is this at all possible, or are there any good workarounds that I can use?
My answer is based on the assumption that your usage indicates use as being a method of the object obj. In which case the way to achieve your objective is to use the same object to store the first parameter to obj.use.
var obj = {
use: function(greeting, fn) {
obj.greeting = greeting;
fn();
}
}
obj.use('hello', function () {
console.log(obj.greeting); //output: 'hello'
});
// Here I want to access the string 'hello'
Well that's easy, you just store the string in a variable whose scope is accessible inside the method:
var greeting = 'hello';
obj.use(greeting, function () {
console.log(greeting); // logs "hello"
});

How add function name to handler click? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a button and I have function which should execute on click.
example:
<button id="button1">bla bla</button>
<script>
var justFunctionName = "function1";
var function1 = function()
{
alert("!");
}
$("#button1").click(justFunctionName);
</script>
HTML
<button id="button1">bla bla</button>
jQuery
var justFunctionName = "function1";
function function1()
{
alert("!");
}
$("#button1").on("click", window[justFunctionName]);
See working jsFiddle demo
$("#button1").click(justFunctionName);
should be
$("#button1").click(function1);
var justFunctionName = "function1";
This is assigning the string function1 to the variable justFunctionName.
If you were to do: console.log('justFunctionName'); you would end up with the following result:
>function1
Therefore this variable assignment is completely irrelevant for what you are hoping to achieve. Instead of just assigning a variable to a function you are assigning a variable to a variable which is assigned to a function.
Now take a look at what you are doing here:
var function1 = function () {
alert("!");
};
This is assigning a variable function1 to the function doing the alert. In this instance, think of the variable as a reference to the function. In order to have the button trigger the alert, you need to call the reference to the function (in this case function1):
$("#button1").click(function1);

how to avoid a function in javascript to get called with new keyword [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Any function in JavaScript can be called using new keyword, is there any way to create a function which cannot be called with new keyword.
EDIT
I am just curious, if it is possible to do it? Since I try to execute new alert(), where alert looks like a function to me, i got an error. I am dont know why it happened with alert and if there is any way to achieve same with normal functions in JavaScript.
I suppose you could perform a test on this:
function test() {
if (this instanceof test) {
throw new Error('yikes');
}
}
new test(); // yikes!
test();
No, new is one of the key features of JS, you can only change a behavior of your function to act the same with new and without new using bind():
function_to_call = function_to_call.bind(your_object);
function_to_call will always have your_object as context.
There is a work-around for that.
function Foo() {
if (this instanceof Foo) {
//Calling with new keyword
console.log("Calling with new keyword");
} else {
//calling without new keyword
console.log("Calling without new keyword");
}
}
The idea is to check if we’re currently inside the function itself and not in an instantiated version of the function.
Read more at John Resig's blog.

Is there any catch/gotcha in this JavaScript boilerplate? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm developing a website with jQuery and organize code into several script files.
If I didn't get it wrong, there's a best practice of organizing your code like this boilerplate (which creates a separated scope and set the undefined value correctly):
(function($, undefined) {
$(document).ready(function() {
// code here
});
})(jQuery);
In my case, I will also rely on some external configuration outputted by some server-side script, say it is stored as global variable site_config. So currently my script boilerplate is:
(function(window, undefined) {
var document = window.document;
var $ = window.jQuery;
var config = window.site_config;
// equivalent to $(document).ready(function() {...
$(function() {
// code here using `config`
});
})(window);
So my question is: is there any catch/gotcha in this boilerplate?
Specifically:
is it OK to pass in window explicitly? (suppose the wrapper function is in global scope)
should I use window.document or jQuery.document? If both are wrong, how to reference correctly?
is it OK to pass in window explicitly?
It's OK, but unnecessary (see Why do I pass the window object in to the module pattern?).
should I use window.document or jQuery.document? If both are wrong, how to reference correctly?
jQuery.document is wrong, the jQuery function object has no such property. However, it would be fine to just use document, as it is a global and non-writable variable.

Categories

Resources