Object.prototype.toString.call([1,2,3])=="[object Array]";
2. js中function的this
参考:javascript之function的apply(), call()
在 javascript 中, function 中的 this 指代的是: 调用 function 执行时的上下文。
也就是说,调用哪个对象的 function,this就指代哪个对象。默认是 window 对象。
Function.prototype.apply():
- The apply() method calls a function with a given this value and arguments provided as an array.
- 指定函数执行时的上下文对象 this,和执行参数,并执行函数。
例:
- var x=10;
- var o ={ x: 15 };
- function foo(){
- alert(this.x);
- }
- foo(); // 10
- foo.call(o); // 15
当调用 foo() 时,this是指向window的(所有的全局变量就是window的属性)。
当调用 foo.call(o) 时,this指向给定的 o 。
不同点:
apply 可以将参数作为数组的形式传递 (防止参数个数超出)
call 传递参数,必须一个个明确列出来
对匿名函数使用 call() 方法 :
- var animals = [
- {species: 'Lion', name: 'King'},
- {species: 'Whale', name: 'Fail'}
- ];
- for (var i = 0; i < animals.length; i++) {
- (function (i) {
- this.print = function () { //add print method for arguments.
- console.log('#' + i + ' ' + this.species + ': ' + this.name);
- }
- this.print();
- }).call(animals[i], i);
- }
3. $.extend() 和 $.fn.extend()
参考:区别和详解:jQuery extend()和jQuery.fn.extend()
jQuery.extend(): Merge the contents of two or more objects together into the first object.(把两个或者更多的对象合并到第一个当中);
jQuery.fn.extend():Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods.(把对象挂载到jQuery的prototype属性,来扩展一个新的jQuery实例方法)
理解jQuery.extend()
我们先把jQuery看成了一个类,这样好理解一些。jQuery.extend(),是扩展的jQuery这个类。
假设我们把jQuery这个类看成是人类,能吃饭能喝水能跑能跳,现在我们用jQuery.extend这个方法给这个类拓展一个能说话speak()的技能。这样的话,不论是男人,女人,xx人.....等能继承这个技能(方法)了。
可以如下图这样写着:
JQuery.extend({ speak:function(){ alert("how are you!"); } });
$.speak();
这说明$.speak)变成了jQuery这个类本身的方法(object),他现在能"说话"了。
所以,这个扩展也就是所谓的静态方法,只跟这个 类 本身有关。跟你具体的实例化对象是没关系的。
理解 jQuery.fn.extend()
从字面理解嘛,这个拓展的是jQuery.fn的方法。jQuery.fn是啥玩意呢?
jQuery.fn = jQuery.prototype = { init:funtion(selector,context){ //..... } }
所以jQuery.fn.extend拓展的是jQuery对象(原型的)的方法啊!
对象是啥?就是类的实例化嘛,例如$("#abc") ,$(div)
那就是说,jQuery.fn.extend拓展的方法,你得用在jQuery对象上面才行啊!
$.fn.extend({ speak:function(){ alert("how are you!"); } });
调用:
$("div").speak();
两者区别总结:
1、两者调用方式不同:
jQuery.extend(),一般由传入的全局函数来调用,主要是用来拓展个全局函数,如$.init(),$.ajax();
jQuery.fn.extend(),一般由具体的实例对象来调用,可以用来拓展个选择器,例如$.fn.each();
2、两者的主要功能作用不同:
jQuery.extend(object); 为扩展jQuery类本身,为自身添加新的方法。
jQuery.fn.extend(object);给jQuery对象添加方法
3、大部分插件都是用jQuery.fn.extend()