通过原型,模拟jquery中的部份功能

我们来聊一下关于jquery部份功能的实现.首先我们要知道构造函数和原型这些基本的概念。
我们来看下最为简单的构造函数。
function Base(){
this.name = “咖啡”
this.age = 20
}
var base = new Base();
alert(base.name) //咖啡
我们可以通过构造函数,然后在通过对象实例化,可以获取到构造函数里面的属性,这是没有问题的。那么我们看下原型(prototype)是怎么工作的。
function Base(){
this.name = “咖啡”
this.age = 20
}
Base.prototype.sex = “男”
var base = new Base();
alert(base.sex) //男
我们可以通过prototype的方式,给我们的构造函数,添加属性和方法。

OK,那么我们来看下怎么通过构造函数和原型编写jquery中的部份功能.

function Base(){
}
Base.prototype.getId = function(id){
return document.getElementById(id)
}
前台调用:
var base = new Base()
base.getId(“box”) //获取到id为box的元素
这种方式来获取id的元素是没有问题的,但是这种方式没有办法实现连缀的功能,因为你并没有返回一个base对象,所以我们需要改造一下这个代码.
function Base(){
//建立一个空数组
this.elements = []

}
//获取id
Base.prototype.getId = function(id){
this.elements.push(document.getElementById(id))
return this //返回base对象
}
前台调用:
var base = new Base()
base.getId(“box”) //获取到id为box的元素,并且可以返回base对象

//获取class类名

Base.prototype.getClass = function(className){
var all = document.getByTagName(“*”)
for(var i=0;i

猜你喜欢

转载自blog.csdn.net/only_ruiwen/article/details/80903440
今日推荐