. .
, ?
.
(callable) ' . .
name
.
name .
function sayHi() {
alert("Hi");
}
alert(sayHi.name); // sayHi
.
let sayHi = function() {
alert("Hi");
};
alert(sayHi.name); // sayHi ( !)
.
function f(sayHi = function() {}) {
alert(sayHi.name); // sayHi ( !)
}
f();
'contextual name . .
name .
let user = {
sayHi() {
// ...
},
sayBye: function() {
// ...
}
}
alert(user.sayHi.name); // sayHi
alert(user.sayBye.name); // sayBye
. , name . .
//
let arr = [function() {}];
alert( arr[0].name ); // < >
// name
.
length
length . .
function f1(a) {}
function f2(a, b) {}
function many(a, b, ...more) {}
alert(f1.length); // 1
alert(f2.length); // 2
alert(many.length); // 2
.
, length (type introspection) .
question handler ask .
ask . ask .
- , OK
- , OK Cancel
handler.length handler .
, ask handler.length .
function ask(question, ...handlers) {
let isYes = confirm(question);
for(let handler of handlers) {
if (handler.length == 0) {
if (isYes) handler();
} else {
handler(isYes);
}
}
}
// OK ,
// Cancel ,
ask(" ?", () => alert('OK .'), result => alert(result));
( length ) (polymorphism) . .
.
counter .
function sayHi() {
alert("Hi");
// .
sayHi.counter++;
}
sayHi.counter = 0; //
sayHi(); // Hi
sayHi(); // Hi
alert( ` : ${sayHi.counter}` ); // : 2
sayHi.counter = 0 counter . counter let counter .
, . . .
function makeCounter() {
// let count = 0 ()
function counter() {
return counter.count++;
};
counter.count = 0;
return counter;
}
let counter = makeCounter();
alert( counter() ); // 0
alert( counter() ); // 1
count .
?
count . count . count . count .
function makeCounter() {
function counter() {
return counter.count++;
};
counter.count = 0;
return counter;
}
let counter = makeCounter();
counter.count = 10;
alert( counter() ); // 10
.
(Named Function Expression, NFE) .
, .
let sayHi = function(who) {
alert(`Hello, ${who}`);
};
.
let sayHi = function func(who) {
alert(`Hello, ${who}`);
};
? "func" ?
. function "func" .
.
sayHi() .
let sayHi = function func(who) {
alert(`Hello, ${who}`);
};
sayHi("John"); // Hello, John
func . .
- .
- .
sayHi . sayHi who , "Guest" .
let sayHi = function func(who) {
if (who) {
alert(`Hello, ${who}`);
} else {
func("Guest"); // func .
}
};
sayHi(); // Hello, Guest
// func .
func(); // Error, func is not defined ( .)
sayHi func ?
.
let sayHi = function(who) {
if (who) {
alert(`Hello, ${who}`);
} else {
sayHi("Guest");
}
};
sayHi . , null .
let sayHi = function(who) {
if (who) {
alert(`Hello, ${who}`);
} else {
sayHi("Guest"); // TypeError: sayHi is not a function
}
};
let welcome = sayHi;
sayHi = null;
welcome(); // sayHi !
sayHi . (local) sayHi sayHi , sayHi null .
.
.
let sayHi = function func(who) {
if (who) {
alert(`Hello, ${who}`);
} else {
func("Guest"); // .
}
};
let welcome = sayHi;
sayHi = null;
welcome(); // Hello, Guest ( )
"func" (function-local) . . .
sayHi welcome func ' .
' , . .
. .
.
.
name. , ( ) .length.
. .
. .
. jQuery $ . lodash _ _.clone, _.keyBy . lodash . . .
, .
<code>,<pre>. 10 plnkr, JSBin, codepen .