Javascript中最好的特性是对函数的实现,函数是javascript的基础模块单元,用于代码复用,信息隐藏,组合调用。函数即对象的行为。 函数,既是方法,又是类。参数函数的参数是一个arguments数组。函数内部可以迭代访问参数。
类似 java 的 变长参数 public void fun(String ... string){}; 不过java是强类型,有类型限制,而javascript是弱类型,没有类型限制。返回值javascript的函数总是会返回一个值。默认返回undefined。
声明函数的方式
function functionName() { } var functionName = function() { } 这两种方式看起来一样,其实是不同的 alert(test2()); // function语句在解析时会被提升,不管function放到哪里,它会被移动到被定义时所在作用域的顶层。 //这种方式不会报错。 /*function test2 (){ return { id : 1 } }*/ //这种方式 alert(test2()); 会报错,因为 test2 这个变量并没有声明 var test2 = function(){ return { id : 1 } }this,(this 永远指向被调用的对象,它的值取决于调用模式。)方法调用模式, 当一个函数被保存为对象的属性时,被称为方法。当此方法被调用时,this是这个对象。 如 : var person = { id : 1, increment : function(in) {
alert(this === person); // true,这里的this就是person这个对象 this.id += (typeof in === 'number' ? in : 1); } } person.increment(1); document.writeln(person.id); 函数调用模式, 当一个函数并非对象的属性时。 如 : function foo() = { alert(this); } foo(); 这里的this是window对象,也就是全局对象。 问题 : 函数内部调用函数,它是用window对象来调用的,而不是调用外部函数的对象 var MyObject = function(){ this.value = 0; var that = this; alert(this +"-"+that); var increment = function(ar) { alert(this +"-"+that); that.value += (typeof ar !== 'number' ? 1 : ar); }; increment(); // 之所以要用that ,是因为这个地方是javascript的一个设计错误。 函数内部调用函数,它是用window对象来调用的,而不是调用外部函数的对象 }
构造器调用模式, 使用new调用构造器,这里的this指的是对象的引用(对象的地址)。 如 : var Person = function (name) { this.name = name; } Person.prototype.getName = function() { return this.name; } var person = new Person("ldh");//this 即 person alert(person.getName()); apply调用模式。 手动绑定this的值。
使用apply() 和 call()方法
转载于:https://www.cnblogs.com/shouwangzhe-/p/3935752.html
