第四章 函数
上一章写到原型 Prototype ,
对象字面量产生的对象连接到 Object.prototype,函数对象连接到 Function.prototype,须知函数本身也是Object
每个对象在创建时,也会随带一个prototype属性,即为构造器对象。
函数字面量
function(a,b){
return a+b;
}
共有四部分 第一部分function 保留字, 第二部分 函数名 省略, 第三部分 括号及一组参数, 第四部分 花括号中的一组语句。
函数调用的两个参数 this, arguments ,四种模式, 方法调用,函数调用,构造器调用,apply调用。
方法调用
函数调用
当一个函数并非一个对象的属性时,它被当成一个函数来调用
var add =function(a,b){
return a+b;
}
var sum=add(3,3);
当函数以此模式调用时, this 被绑定到全局变量,this.value不是指向的myObject.value 。兼容的话,需要如下处理
这样就能myObject的值就变了
构造器调用模式
var Quo= function(str){ this.status =str };
Quo.prototype.getStatus=function(){
return this.value;
}
var myQuo =new Quo("confused");
myQuo.getValue()
调用模式
var array=[3,4];
var sum =add.apply(null,array);
参数
返回 return,
异常 try {}catch(e){}、throw
给类型添加方法:
Function.prototype.method=function (name, func){
this.prototype[name]=func;
return this;
}
递归 汉诺塔的问题
作用域、闭包
var quo= function( status){
return{
get_status:function(){
return status;
}
};
};
var myQuo=quo("amazed");
myQuo.get_status();
通过调用方法模式,返回的是一个包含方法的对象。该函数可以访问它被创建时所处的上下文环境。 这就被称为闭包。
第五章 继承
定义constructor 函数,使用 类 替换原型 prototype
Function.method(‘’,function(parent){
this.prototype=new Parent();
return this;
});
这样子就可以通过闭包,以级联的样式编程。
函数的四种调用方式, 方法调用及函数调用,是作为对象的方法,或者把方法做为对象的值。
构造器调用 是作为函数,需要初始化new
apply是将方法挂在对象上, 一个参数是传给对象的this的值,第二个参数是方法需要的值。
闭包的话,返回对象,通过调用函数返回一个对象。