//先从整体、全局的看,jQuery的源码几乎都在下面的代码中:
(function(){
//...
})(window);
//第一个括号里面是个匿名函数,第二个括号表示马上执行第一个括号里面的代码。
//首先明白,javascript里面是没有命名空间的,要保证你的javascript函数、对象与其他的不冲突,这里用了javascript的一个技巧:你的所有javascript函数、对象都在一个匿名函数里面定义,确保了所定义的函数、对象的有效范围,起到了命名空间的作用。既然作用范围在这个匿名函数中,怎么被别人使用呢?下面看它的下面代码:
(function() {
var jQuery = window.jQuery = window.$ = function() {
//alert(1);
};
})(window);
window.$();
//这里让jQuery库中最重要的对象jQuery成为了window对象的一个属性,这样就可以在其他地方像使用document(document也是window的一个属性)一样使用jQuery了。
js继承有5种实现方式:
继承第一种方式:对象冒充
通过以下3行实现将Parent的属性和方法追加到Child中,从而实现继承
第一步:this.method是作为一个临时的属性,并且指向Parent所指向的对象,
第二步:执行this.method方法,即执行Parent所指向的对象函数
第三步:销毁this.method属性,即此时Child就已经拥有了Parent的所有属性和方法
function Parent(username){
this.username=username;
this.hello=function(){
alert(this.username);
}
}
function Child(username,password){
this.methed=Parent;
this.methed(username);
delete this.methed;
this.password=password;
this.world=function(){
alert(this.password);
}
}
var parent = new Parent("zhangsan");
var child = new Child("lisi","123456");
parent.hello();//zhangsan
child.hello();//lisi
child.world();//123456
继承第二种方式:call()方法方式
call方法是Function类中的方法
call方法的第一个参数的值赋值给类(即方法)中出现的this
call方法的第二个参数开始依次赋值给类(即方法)所接受的参数
function Parent(username){
this.username=username;
this.hello=function(){
alert(this.username);
}
}
function Child(username,password){
//此时,第一个参数值this也就是Child传递给了Parent类(即方法)中出现的this,而第二个参数username则赋值给了Parent类(即方法)的username
Parent.call(this, username);
this.password=password;
this.world=function(){
alert(this.password);
}
}
var parent = new Parent("zhangsan");
var child = new Child("lisi","123456");
parent.hello();//zhangsan
child.hello();//lisi
child.world();//123456
继承的第三种方式:apply()方法方式
apply方法接受2个参数,
A、第一个参数与call方法的第一个参数一样,即赋值给类(即方法)中出现的this
B、第二个参数为数组类型,这个数组中的每个元素依次赋值给类(即方法)所接受的参数
function Parent(username){
this.username=username;
this.hello=function(){
alert(this.username);
}
}
function Child(username,password){
Parent.apply(this, new Array(username));
this.password=password;
this.world=function(){
alert(this.password);
}
}
var parent = new Parent("zhangsan");
var child = new Child("lisi","123456");
parent.hello();//zhangsan
child.hello();//lisi
child.world();//123456
继承的第四种方式:原型链方式,即子类通过prototype将所有在父类中通过prototype追加的属性和方法都追加到Child,从而实现了继承
function Parent(){}
Parent.prototype.hello="hello";
Parent.prototype.sayHello=function(){
alert(this.hello);
}
function Child(){}
//将Parent中将所有通过prototype追加的属性和方法都追加到Child,从而实现了继承
Child.prototype=new Parent();
Child.prototype.world="world";
Child.prototype.sayWorld=function(){
alert(this.world);
}
var c = new Child();
c.sayHello();
c.sayWorld();
原文:http://my.oschina.net/guozhenzhen/blog/340292