函数调用
1.作为普通函数调用
function hello() {
console.log("hello,world");
}
hello();
2.匿名函数调用
var world = function() {
console.log("匿名函数调用");
}
-+~function() {
console.log("匿名函数调用");
}();
3.阶乘
function fact(num) {
var result = 1;
if(num <= 1) {
return result;
} else {
for(var i = 1; i <= num; i++) {
result = result * i;
}
return result;
}
}
4.递归调用
function factorial(num) {
if(num <= 1) {
return 1;
}
return num * factorial(num - 1);
}
console.log(factorial(5));
5.对象方法调用
var obj = {
name: "xiaoming",
sayhi: function() {
console.log("hello");
},
0: function() {
console.log("zero");
},
"0abc": function() {
console.log("0abc");
}
}
obj.sayhi();
obj[0]();
obj["0abc"]();
var prop = "0abc";
obj[prop]();
6.构造函数调用
function test() {
console.log("测试");
}
var result1 = test();
var result2 = new test();
console.log(result1);
console.log(result2);
var dd = new Date();
console.log(dd.getFullYear());
var arr = new Array();
arr[1] = 10;
console.log(arr);
7.间接调用
function add(m , n) {
return m + n;
}
var result1 = add(1,2);
var result2 = add.call(window,2,3);
var result3 = add.apply(window,[4,5]);
console.log(result1);
console.log(result2);
console.log(result3);
var name = "xiaoming";
var person = {
name : "xiaohong";
print : function() {
console.log(this.name);
}
}
person.print();
persom.print.call(person);
persom.print.apply(person);
8.函数参数
function hello() {
console.log("hello,world");
}
hello();
function add(m,n) {
console.log(arguments);
console.log(arguments[0]);
console.log(arguments[1]);
console.log(arguments[2]);
if(arguments.length != add.length) {
console.log("参数个数不一致");
return;
}
console.log(arguments.callee === add);
return m + n;
}
var result1 = add(1,2);
console.log(result1);
var result2 = add(1,"2");
console.log(result2);
function factorial(num) {
if(num <= 1) {
return 1;
}
return num * arguments.callee(num - 1);
}
console.log(factorial(5));
function add(m,n) {
if (arguments.length != arguments.callee.length) {
return;
}
return m + n;
}
console.log(add(1,2));
var h = -function() {}();
console.log(h);
var person = {
eat: function() {
console.log("吃饭");
return this;
},
run: function() {
console.log("跑步");
return this;
},
study: function() {
console.log("学习");
return this;
}
}
var a = person.eat();
person.eat().run().study();
console.log(a === person);