views:

96

answers:

5

Hi, i've written this peace of code:

var a=function(){
};

a.name="test";
a.prop="test2";

Now if i debug the code with the console:

console.log(a.name);
console.log(a.prop);

In Firefox i get a.name="test" and a.prop="test2", while in Safari and Chrome i get a.prop="test2" but a.name="".

It seems that there's no way to assign a "name" property on a function in Webkit browsers. Do you know why? But the most important thing is, do you know a workaround for that?

A: 

Some words are reserved in JS but some browsers still support them.

Take a look here : http://www.quackit.com/javascript/javascript_reserved_words.cfm

Kaaviar
Irrelevant. `name` is not a reserved word in JavaScript. The issue is that Function objects already have a `name` property in some browsers.
Tim Down
Even if `name` was a reserved word, it wouldn't matter because you can use reserved words as property names.
Tim Down
+4  A: 

Function instances have a non-standard name attribute which will return the name of the function, or an empty string if the function is anonymous (like yours). Browsers will react differently when you try to write to the attribute, so I suggest using another property-name.

J-P
I think you're right. So there's no way to solve the problem right?
mck89
A: 

why are you trying to assign properties to method? that seems like it should be a violation of some procedure or practice. if you want both a method and properties available, make a new object to contain them.

lincolnk
Functions are objects and can quite happily have properties assigned to them. So long as you avoid attempting to overwrite the built-in properties such as `name`, it's a perfectly acceptable thing to do.
Tim Down
A: 

It appears that you can't change the name of an anonymous/lambda function. If you'd like to set the name, you need to do something like var a=function b() {} then you can set the name.

Wayne Werner
I don't think so. The name property will still be read-only, in Chrome at least.
Tim Down
A: 

As you can see, "name" is not an option, so:

var a = function(){
};


a.props={name:"test",prop:"test2",anyKey:"anyValue"};

may be a solution.

Poliveira