日期:2014-05-16 浏览次数:20672 次
二.函数
var add = function(a,b){
return a + b;
};
?var myObject = {
value : 0,
increment : function(inc){
// 方法this可以访问对象的属性。 this到对象的绑定发生在调用时。
// 这种延迟绑定使得函数可以对this进行高度复用.
// 通过this可以访问所属对象上下文的方法称为公共方法(!).
this.value += typeof inc === "number" ? inc : 1;
}
};
myObject.increment(); // 使用属性存取表达式调用,属于方法调用模式.
document.writeln(myObject.value);
myObject.increment(2);
document.writeln(myObject.value);
?var sum = add(3,4); // 7?? 当函数以此模式调用时,this被绑定到全局对象。这是JS语言设计上的一个错误。在正确设计时,当函数中的内部函数被调用时,this应该仍然绑定到外部函数的this变量.这个设计错误的后果是方法不能利用内部函数来帮助它工作,因为内部函数的this被绑定了错误的值, 所以不能共享该方法对原对象的访问权。幸运的是,有一个很容 易的解决方案。通过定义一个临时变量.
myObject.double = function(){
var that = this; // 保存外部函数的上下文.
var helper = function(){
that.value = add(that.value,that.value);
};
helper(); // 函数方式调用helper. 此时helper内部的context 是 window. 所以需要定义 that.
};
myObject.double();
document.writeln(myObject.value);
?// 按照约定,对于构造器变量. 它们需要以开头大写的格式来命名。
var Quo = function(string){
this.status = string;
};
// 为所有Quo 的实例提供一个get_status方法.
Quo.prototype.get_status = function(){
return this.status;
};
var myQuo = new Quo("confused");
document.writeln(myQuo.get_status()); // 令人困惑的结果.
?var args = [3,4];
var sum = add.apply(null,args); // context 为null 时表示将context 绑定到 window.
document.writeln(sum);
var statusObject = {status : "A-OK"};
// 使用statusObject 作为函数上下文去调用 get_status方法.
var status = Quo.prototype.get_status.apply(statusObject);
document.writeln(status);
? ?apply传入的是一个参数数组,也就是将多个参数组合成为一个数组传入,而call则作为call调用的参数传入(从第二个参数开始)。如 func.call(func1,var1,var2,var3)对应的apply写法为:func.apply(func1,[var1,var2,var3])使用apply的好处是可以直接将当前函数的arguments对象作为apply的第二个参数传入.var sum = function(){