Why doesn't "function sayHi.alternate () {}" work?
I am having a hard time understanding Static scope in Javascript. Can anyone please explain the difference between 开发者_开发百科the below two functions
It works fine if I do
function sayHi(){
alert("Hi");
}
sayHi.alternate=function(){
alert("Hola");
}
sayHi();
sayHi.alternate();
But doenst work if I do
function sayHi(){
alert("Hi");
}
function sayHi.alternate(){
alert("Hola");
}
sayHi();
sayHi.alternate();
As usual Thanks
function sayHi.alternate(){
alert("Hola");
}
...will give you a syntax error. That's because you cannot name your function sayHi.alternate
.
However, since everything in Javascript is an object, including functions, you can simply treat your sayHi
function as an object, and add a new method to it with:
sayHi.alternate = function(){
alert("Hola");
}
When you write function sayHi.alternate
you're trying to create a function called sayHi.alternate
. Functions can't contain a period in their names, so sayHi.alternate
is an invalid function name.
When you create sayHi.alternate= function
you're creating a function called alternate
inside the object sayHi
.
This isn't valid javascript:
function sayHi.alternate(){
You can't assign a property when declaring a function this way. You can only define a name to be used for the function. That's why the other form is used when you're assigning it to an object property or assigning to a variable.
精彩评论