Javascript functions string parameters

Javascript – Passing string parameter in JavaScript function

I was trying to pass a string to a JavaScript function.

I’m using this simple code-

    name = "Mathew"; document.write("") function myfunction(name)  

But in the console it’s giving an error like Uncaught SyntaxError: Unexpected token > .

Best Solution

Javascript – How do JavaScript closures work

A closure is a pairing of:

A lexical environment is part of every execution context (stack frame) and is a map between identifiers (ie. local variable names) and values.

Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to «see» variables declared outside the function, regardless of when and where the function is called.

If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.

In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret :

function foo() < const secret = Math.trunc(Math.random()*100) return function inner() < console.log(`The secret number is $.`) > > const f = foo() // `secret` is not directly accessible from outside `foo` f() // The only way to retrieve `secret`, is to invoke `f`

In other words: in JavaScript, functions carry a reference to a private «box of state», to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.

And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.

If JavaScript did not have closures, then more states would have to be passed between functions explicitly, making parameter lists longer and code noisier.

So, if you want a function to always have access to a private piece of state, you can use a closure.

. and frequently we do want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating state with functionality.

In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, secret remains available to the function object inner , after it has been returned from foo .

Uses of Closures

Closures are useful whenever you need a private state associated with a function. This is a very common scenario — and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.

Private Instance Variables

In the following code, the function toString closes over the details of the car.

function Car(manufacturer, model, year, color) < return < toString() < return `$$ ($, $)` > > > const car = new Car('Aston Martin','V8 Vantage','2012','Quantum Silver') console.log(car.toString())

Functional Programming

In the following code, the function inner closes over both fn and args .

function curry(fn) < const args = [] return function inner(arg) < if(args.length === fn.length) return fn(. args) args.push(arg) return inner >> function add(a, b) < return a + b >const curriedAdd = curry(add) console.log(curriedAdd(2)(3)()) // 5

Event-Oriented Programming

In the following code, function onClick closes over variable BACKGROUND_COLOR .

const $ = document.querySelector.bind(document) const BACKGROUND_COLOR = 'rgba(200,200,242,1)' function onClick() < $('body').style.background = BACKGROUND_COLOR >$('button').addEventListener('click', onClick)

Modularization

In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions tick and toString close over the private state and functions they need to complete their work. Closures have enabled us to modularise and encapsulate our code.

let namespace = <>; (function foo(n) < let numbers = [] function format(n) < return Math.trunc(n) >function tick() < numbers.push(Math.random() * 100) >function toString() < return numbers.map(format) >n.counter = < tick, toString >>(namespace)) const counter = namespace.counter counter.tick() counter.tick() console.log(counter.toString())

Examples

Example 1

This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables themselves. It is as though the stack-frame stays alive in memory even after the outer function exits.

function foo() < let x = 42 let inner = function() < console.log(x) >x = x+1 return inner > var f = foo() f() // logs 43

Example 2

In the following code, three methods log , increment , and update all close over the same lexical environment.

And every time createObject is called, a new execution context (stack frame) is created and a completely new variable x , and a new set of functions ( log etc.) are created, that close over this new variable.

function createObject() < let x = 42; return < log() < console.log(x) >, increment() < x++ >, update(value) < x = value >> > const o = createObject() o.increment() o.log() // 43 o.update(5) o.log() // 5 const p = createObject() p.log() // 42

Example 3

If you are using variables declared using var , be careful you understand which variable you are closing over. Variables declared using var are hoisted. This is much less of a problem in modern JavaScript due to the introduction of let and const .

In the following code, each time around the loop, a new function inner is created, which closes over i . But because var i is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of i (3) is printed, three times.

function foo() < var result = [] for (var i = 0; i < 3; i++) < result.push(function inner() < console.log(i) >) > return result > const result = foo() // The following will print `3`, three times. for (var i = 0; i

Final points:

  • Whenever a function is declared in JavaScript closure is created.
  • Returning a function from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.
  • Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using eval(‘var foo = …’) .
  • When you use new Function(…) (the Function constructor) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.
  • A closure in JavaScript is like keeping a reference (NOT a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.
  • A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
  • A new set of local variables is created every time a function is called.
  • Douglas Crockford’s simulated private attributes and private methods for an object, using closures.
  • A great explanation of how closures can cause memory leaks in IE if you are not careful.
  • MDN documentation on JavaScript Closures.
Javascript – Remove properties from objects (JavaScript)

To remove a property from an object (mutating the object), you can do it like this:

delete myObject.regex; // or, delete myObject['regex']; // or, var prop = "regex"; delete myObject[prop]; 
var myObject = < "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" >; delete myObject.regex; console.log(myObject);

For anyone interested in reading more about it, Stack Overflow user kangax has written an incredibly in-depth blog post about the delete statement on their blog, Understanding delete. It is highly recommended.

If you’d like a new object with all the keys of the original except some, you could use the destructuring.

let myObject = < "ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*" >; const = myObject; console.log(newObj); // has no 'regex' key console.log(myObject); // remains unchanged

Источник

Pass a string parameter in an onclick function

with result.name for example equal to string «Add». When I click on this button, I have an error that says that «Add is not defined». Since this function call works perfectly with a numeric parameter, I assume that it has something to do with the symbols «» in the string. How can I fix this problem?

27 Answers 27

It looks like you’re building DOM elements from strings. You just need to add some quotes around result.name:

You should really be doing this with proper DOM methods though.

var inputElement = document.createElement('input'); inputElement.type = "button" inputElement.addEventListener('click', function()< gotoNode(result.name); >); ​document.body.appendChild(inputElement);​ 

Just be aware that if this is a loop or something, result will change before the event fires and you’d need to create an additional scope bubble to shadow the changing variable.

Hi @david..I have one doubt. I want to pass multiple argument in that onclick..how it possible? can you make useful for me.

@david,thanks it solved my string parameter issue but now i have to pass (string, boolean). what to do for that?

A couple of concerns for me with respect to using string escape in onClick and as the number of arguments grow, it will become cumbersome to maintain.

The following approach will have a one hop — On click — take the control to a handler method and handler method, based on the event object, can deduct the click event and corresponding object.

It also provides a cleaner way to add more arguments and have more flexibility.

The advantage here is that we can have as many arguments (in above example, data-arg1, data-arg2, etc.) as needed.

Источник

[javascript] Passing string parameter in JavaScript function

I was trying to pass a string to a JavaScript function.

I’m using this simple code-

    name = "Mathew"; document.write("") function myfunction(name)  

But in the console it’s giving an error like Uncaught SyntaxError: Unexpected token > .

The answer is

Rename your variable name to myname , bacause name is a generic property of window and is not writable in the same window.

var myname = "Mathew";_x000D_ document.write('');_x000D_ function myfunction(name)

The question has been answered, but for your future coding reference you might like to consider this.

In your HTML, add the name as an attribute to the button and remove the onclick reference.

In your JavaScript, grab the button using its ID, assign the function to the button’s click event, and use the function to display the button’s data-name attribute.

var button = document.getElementById('button'); button.onclick = myfunction; function myfunction()

You can pass string parameters to JavaScript functions like below code:

I passed three parameters where the third one is a string parameter.

var btn =""; // Your JavaScript function function RoomIsReadyFunc(ID, RefId, YourString)

Better to use « than «». This is a more dynamic answer.

Источник

Javascript: How to pass a function with string parameters as a parameter to another function

The context of this question is that on the onClick I need to call a javascript function that will make an ajax call to the url I provide. It will open a modal div with OK and Cancel buttons. Up to here it’s fine. But then I also needed to tell the javascript function another function with other parameters and urls to be called when an OK button is clicked in the new div. And another one for the Cancel button. The problem is I can’t manage to pass the second argument properly as it doesn’t escape properly and gives me javascript errors. I have done a search for other similar Javascript questions in SO but non of them seem to cover what I need to do. Anybody knows how could I pass this kind of string parameters to the javascript function? Or maybe there’s another better solution of passing this things that I didn’t think of. Thanks in advance

3 Answers 3

One way would be to just escape the quotes properly:

In this case, though, I think a better way to handle this would be to wrap the two handlers in anonymous functions:

And then, you could call them from within myfunction like this:

function myfunction(url, onOK, onCancel) < // Do whatever myfunction would normally do. if (okClicked) < onOK(); >if (cancelClicked) < onCancel(); >> 

That’s probably not what myfunction would actually look like, but you get the general idea. The point is, if you use anonymous functions, you have a lot more flexibility, and you keep your code a lot cleaner as well.

Источник

Читайте также:  Загрузка больших файлов через php
Оцените статью