1 /*
2 1.把函数作为参数、匿名函数作为参数传递到函数
3 */
4 function dogEat(food) {
5 console.log("dog eat " + food);
6 }
7
8 function catEat(food) {
9 console.log("cat eat" + food);
10 }
11
12 function eat(food, eatFunction) {
13 eatFunction(food);
14 }
15
16 eat("bone", dogEat);
17 eat("fish", catEat);
18 eat("rice", function(x) { console.log("eat " + x); })
19 /*
20 2.模拟实现类似onClick函数
21 */
22
23 var server = {
24 'successReq': "req-success",
25 'successRes': "res-success",
26 'failReq': "req-faied",
27 'failRes': "res-faied",
28 'onFunc': function(type, callback) {
29 switch (type) {
30 case 'success':
31 callback(this.successReq, this.successRes);
32 break;
33 case 'fail':
34 callback(this.failReq, this.failRes);
35 break;
36 default:
37 console.log("No type match!");
38 break;
39 }
40 }
41 };
42
43 var obj1 = Object.create(server);
44
45
46 function display(req, res) {
47 console.log("dis-req: " + req + " dis-res: " + res);
48 }
49
50 obj1.onFunc("success", display); //$("#button").on('click',xxxFunc);模拟on函数
51
52 obj1.onFunc("fail", function(res, req) {
53 console.log("failed: " + res + req);
54 })
1 /** 3.对象的某个属性是函数 **/
2
3 obj对象的func属性指向匿名函数
4 var obj = {
5 func:function (){
6 console.log("func");
7 }
8 };
9
10 obj.func // [Function]
11 obj.func() //调用函数,控制台打印 func
12
13 obj对象的func属性指向函数f
14 var obj = {
15 func:function f(){
16 console.log("func");
17 }
18 };
19
20 obj.func // [Function: f]
21 obj.func() //调用函数,控制台打印 func
22
23 属性指向有名称的函数似乎没什么用……