您的位置:首页 > Web前端 > JQuery

jquery源码解读

2015-04-01 20:10 357 查看
我很好奇jquery中的调用函数的方法,比如jQuery().hide()等价于$().hide()
但是在jquery中没有用new运算符来实现实例化,那么可以想象其在构造函数中便返回了它的实例:
var aQuery = function(selector, context) {

return aQuery.prototype.init();

}

aQuery.prototype = {

init: function() {

this.age=23;

return this;

},

name: function() {

return this.age

},

age: 20

}

aQuery().name();
在这里我们可以看到可以直接调用aQuery()而不用使用关键字new先去实例化。但是同时在这里产生一个新的问题,那就是aQuery().age会返回什么值,根据测试返回的是23,那么我们再去看this所代表对象中的属性和值
var aQuery = function(selector, context) {

return aQuery.prototype.init();

}

aQuery.prototype = {

init: function() {

this.age=23;

return this;

},

name: function() {

return this.age

},

age: 20

}

var simple = aQuery();

var s = ""; //这是一个全局变量

function check(object){

for(prop in object) {

s += prop+":"+object[prop]+";";

}

}

check(simple);

alert(simple);
这样我们会看到返回的对象中的内容是什么,那么这里为什么aQuery().age会返回23呢?我觉得应该是相同属性被覆盖了,比如
var test = {

name: "kk",

name: 5

}

alert(test["name"]);//=>5
这样可以看出来以上现象产生的原因。另外再说一小点在javascript中的对象中如果属性的值是字符串那么应该用双引号。

/*var aQuery = function(selector, context) {

return aQuery.prototype.init();

}

aQuery.prototype = {

init: function() {

this.age=23;

return this;

},

name: function() {

return this.age

},

age: 20

}

var simple = aQuery();

var simple1 = aQuery();

simple1.age = 24;

alert(simple.name());//=>24这里为了测试this对象,可以看到simple和simple1分别是两个不一样的对象但是它们却可以互相影响这显然不符合类的实例不是互相影响的*/
所以我们可以这么写:
var aQuery = function() {

return new aQuery.prototype.init();

}

aQuery.prototype = {

init: function() {

return this;

},

name: function() {

return 5;

},

age: 20

}

aQuery.prototype.init.prototype = aQuery.prototype;

var simple = aQuery();

var simple1 = aQuery();

simple1.age = 26;

alert(simple.age);
这样输出的结果依旧是20,说明这种方法返回的对象的实例是不会相互影响的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: