I have the following initialized object, and I want to pass this object through onclick function, is this possible to achieve?
var nameObject = { Name: "Stack", lastName:"Exchange" }
Here is my code:
In the document ready
I have link with onclick
function that is append into html element.
Html:
<div id="test"></div>
Javascript:
$(document).ready(function () {
var nameObject = { Name: "Stack", lastName:"Exchange" };
$("#test").append('<a href="#"'
+'onclick="sendObj(**I want to pass "nameObject" into this function)">'
+'sendObject</a>');
)};
function sendObj(**receive the object**)
{
//nameObject.Name+" "nameObject.lastName;
}
Jsfiddle
Objects can be initialized using new Object (), Object.create (), or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). JavaScript Demo: Expressions - Object initializer 18
Objects are Passed by Reference. In JavaScript, object references are values. Because of this, objects will behave like they are passed by reference: If a function changes an object property, it changes the original value. Changes to object properties are visible (reflected) outside the function.
The Object.create () method will make a new JavaScript Object whose properties can be initialized using dot or bracket notation. In this method, constructor function is used to define the object and this is used to assign value to the properties. An instance of the object is created using new keyword.
JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value. Changes to arguments are not visible (reflected) outside the function.
try this
$(document).ready(function () {
var nameObject = { Name: "Stack", lastName:"Exchange" };
$("#test").append('<a href="#" data-caller>sendObject</a>');
$("#test").on("click", "[data-caller]", function() {
sendObj(nameObject);
});
)};
function sendObj(nameObject)
{
alert(nameObject.Name+" "+nameObject.lastName);
}
working jsfiddle
A more appropriate way of doing what you want is to store the object in the element's data
object, which is what jQuery designates for this very purpose.
Then, assign a click
handler that would call your desired function with the stored data.
$(document).ready(function () {
var name = { Name: "Stack", lastName:"Exchange" };
var a = $('<a href="#">sendObject</a>').data('name', name).on('click',
function(e){
sendObj($(this).data('name'));
});
$("#test").append(a);
});
function sendObj(e)
{
console.log(e);
}
Demo (say hello to console, ditch alert()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With