日期:2014-05-16  浏览次数:20377 次

关于JS中Call方法的使用疑惑?
以下是 JQ jCarouselLite插件的部分代码,我对下面的if (o.beforeStart) o.beforeStart.call(this, vis())甚是疑惑
假如前台调用这个插件,把 beforeStart 配置成 beforeStart = checkUser(id,name);那么if (o.beforeStart) o.beforeStart.call(this, vis()) 中 this 是 checkUser(id,name) ? 还是 插件的对象 o ?
请大家把这个Call 的使用心得分享下吧,俺在此先谢过大家了

(function($) {
$.fn.jCarouselLite = function(o) {
o = $.extend({
  ......
beforeStart: null,
afterEnd: null
},
o || {});
  return this.each(function() {
  function vis() {return f.slice(curr).slice(0, v)};
  function go(a){
  if (o.beforeStart) o.beforeStart.call(this, vis());
  }。。。。。。。

------解决方案--------------------
call() 方法

call() 方法是与经典的对象冒充方法最相似的方法。它的第一个参数用作 this 的对象。其他参数都直接传递给函数自身。例如:

function sayColor(sPrefix,sSuffix) {
alert(sPrefix + this.color + sSuffix);
};

var obj = new Object();
obj.color = "blue";

sayColor.call(obj, "The color is ", "a very nice color indeed.");

在这个例子中,函数 sayColor() 在对象外定义,即使它不属于任何对象,也可以引用关键字 this。对象 obj 的 color 属性等于 blue。调用 call() 方法时,第一个参数是 obj,说明应该赋予 sayColor() 函数中的 this 关键字值是 obj。第二个和第三个参数是字符串。它们与 sayColor() 函数中的参数 sPrefix 和 sSuffix 匹配,最后生成的消息 "The color is blue, a very nice color indeed." 将被显示出来。

要与继承机制的对象冒充方法一起使用该方法,只需将前三行的赋值、调用和删除代码替换即可:

function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(color);
//delete this.newMethod;
ClassA.call(this, sColor);

this.name = sName;
this.sayName = function () {
alert(this.name);
};
}

TIY

这里,我们需要让 ClassA 中的关键字 this 等于新创建的 ClassB 对象,因此 this 是第一个参数。第二个参数 sColor 对两个类来说都是唯一的参数。

------解决方案--------------------
个人的心得,call方法只是单纯地把调用call方法的方法中的this作用域指向call方法的第一个参数开始往上搜索的第一个有效作用域,从call方法的第二个参数起都是传递给调用call方法的call方法。例子:
JScript code

a='a';//这种定义方式为window添加一个a属性,值为'a'
var o={a:1},b={},c,a='a',
fun=function(x){
    alert(this==window);
    alert(this.a);
    if(!isNaN(this.a) && x!==undefined && !isNaN(x))alert(this.a+x);
};
fun.call(o);//先后弹出false 1,作用域为对象o
fun.call(o,2);//先后弹出false 1 3,作用域为对象o,o的a属性为1
fun.call(b);//先后弹出false undefined,作用域为对象b,表示对象b的a属性未定义
fun.call(c);//先后弹出true a,作用域为window,第一行代码为window添加了a属性