js中的prototype使用的问题

base.js

var $ = function ()
{
return new Base();
}

//创建一个数组,来保存获取的节点和节点数组*****************
function Base() {}
Base.prototype.elements = [];

//创建一个数组,来保存获取的节点和节点数组****************
function Base()
{
this.elements = [];
}

//获取ID节点
Base.prototype.getId = function (id) {
this.elements.push(document.getElementById(id));
return this;
};

//获取元素节点
Base.prototype.getTagName = function (tag) {
var tags = document.getElementsByTagName(tag);
for (var i = 0; i < tags.length; i ++) {
this.elements.push(tags[i]);
}
return this;

};

以上****号处这两种写法有什么不同,为什么测试获取的数组的值不一样

html代码

box

段落

段落

段落


demo.js

window.onload = function ()
{
$().getId('box').css('color','red');
alert($().getTagName('p').elements.length);

};

结果:把数组定义在函数体内(*处位置的不同)得到是3,而通过prototype方式,获得数组的长度确实4,这是怎么回事???

Base.prototype.elements设置prototype原型,所有new出来的类都会有elements属性,并且会继承其他实例修改后的值,是共享的

this.elements = [];这样写是动态给实例添加elements对象,只属于此实例,不共享。

$().getId('box').css('color','red');
alert($().getTagName('p').elements.length);
用prototype时,你的第一行添加了一个元素,第二行继续添加3个,因为是共享的,所以你2个实例的elements都是一样的有4个

不用prototype时,是独立的,没构造一次就将elements清空了。所以第一句的添加的对象没有增加到第二句的示例中。你的代码写成这样还好理解点

     var a = $();
    a.getId('box'); //.css('color', 'red');
    var b = $();
    b.getTagName('p');
    alert(b.elements.length);