Reputation: 591
In javaScript, I create objects like shown below. When I parse the objects to a function, I normally name the parameter after the object. [See examples below]. My reasoning for this is if another developer comes along and looks at a function they instantly know the function takes a fooObj, a barObj and laaObj. Question is: Is there any syntax/performance issue that could be related to this. (For example, certain browsers that would have a problem with a parameter name being the same name as a object/'function').
function exampleObj(name, date, wine, cheese) {
this.name = name;
this.date = new Date(date);
this.wine = wine;
this.cheese = cheese;
this.drink = function() {
open(this.wine);
pour(this.wine);
consume(this.wine);
}
this.eat = function() {
unwrap(this.cheese);
getCrackers();
informGromitOfCheese(this.cheese);
consume(this.cheese);
}
}
var example1 = new exampleObj("Foo", "02/05/2014", "Merlot", "Stinky Bishop");
When I pass an object to a function:
// Pass the exampleObj here. Param name == Function name
function foo(exampleObj) { // <-- Is this okay?
alert(exampleObj.name);
}
foo(example1);
Upvotes: 0
Views: 170
Reputation: 1492
Yes, you can use the same name as the parameter. But we normally use Pascal(Upper Camel Case) to name the classes like Date
, Array
.... So you could name the class as ExampleObj
and instance as exampleObj
to avoid confused.
Upvotes: 1
Reputation: 783
sorry, the answer that i posted before may have been misleading, please have a look at this fiddle and see if you can understand what's going on..
http://jsfiddle.net/h_awk/8W92c/
function foo(name, age)
{
this.name = name;
this.age = age;
this.getDetail = function()
{
alert('Name is: ' + this.name + ' age is: ' + this.age);
}
}
function bar(foo)
{
alert(foo.name);
}
bar(new foo('hawk', '24') );
you pass constructor to function bar, then when you call bar, you instantiate foo, it could be done differently.ie.var person = new foo('hawk', 24) and then pass person as a parameter. bar(person) and still get the same result. The this value of foo refers to the function foo hence giving you the expected result, I am sorry and I hope that this helps.. :)
Upvotes: 0