jQuery学习笔记

1、function的作用:产生一个对象 (感觉有点像Java中的Class)
例子如下:
/**
* 该函数是一个对象,该对象是由Function产生的
*/
function Person(){
 
}
alert(Person.constructor);
 
 
Person.a = 5;//给Person对象添加了一个属性为a,值为5
 
function Student(){
 
}
 
Person.b = Student;//给Person对象添加了一个属性为b,值为Student的对象
 
var json = {
aa:'aa'
};
 
Person.c = json;//给Person对象天界另一个属性为c,值为json对象
 
alert(Person.c.aa);
 
2、eval的作用
/**
* 把多个json对象添加了window上
*/
eval("window."+temp.join(".")+"={}");
//把多个function添加到了window上
eval("window."+temp.join(".")+"=function(){}");
 
3、prototype,相当于Java中的属性
例子:
function Person(){
 
}
alert(Person.prototype); //Person是一个函数对象,有一个默认的属性为prototype={},该特点在json对象中是不存在的
 
Person.prototype.aa = 5;//也可以这样写 Person.prottype['aa'] = 5;
 
Person.prototype.bb = function(){
alert("bb");
}
var p = new Person();
alert(p.aa);
 
 
/**
* 模拟一个类,创建一个对象,设置属性,并进行输出
*/
function Student(){
 
}
 
Student.prototype.setId = function(id){
this.id = id;
}
Student.prototype.setName = function(name){
this.name = name;
}
Student.prototype.getId = function(){
return this.id;
}
Student.prototype.getName = function(){
return this.name;
}
 
var s = new Student();
s.setId(4);
s.setName("王二麻子");
alert(s.getId());
alert(s.getName());
 
var s = new Student();
s.setId(4);
s.setName("王二麻子");
alert(s.getId());
alert(s.getName());
 
s.bb = 5;
alert(s.bb);
var ss = new Student();
alert("---------"+ss.bb);
 
 
 
说明:虽然s.bb = 5; 相当于 s对象新建了bb属性,但是 主Student没有增加bb属性,所以会显示“undined”
 
4、继承--基本形式。通过对象的prototype
例子
function Student(){
 
}
Student.prototype.setName = function(name){
this.name = name;
}
Student.prototype.getName = function(){
return this.name;
}
 
function SuperStudent(){
 
}
 
SuperStudent.prototype = Student.prototype;
或者
SuperStudent.prototype = new Student();
var superStudent = new SuperStudent();
 
superStudent.setName("bb");
alert(superStudent.getName());
 
4、继承--封装的形式
/**
* 在extend函数内部定义了一个函数,把传递进来的json对象的每一个key,value值动态的添加到了
* 内部函数的prototype中
* @param {Object} json
*/
namespace("com.itheima12");
com.itheima12.extend = function (json){
/**
* 声明了一个函数
*/
function F(){
 
}
/**
* 遍历json对象中的每一个key,value值,把每一个key,value值赋值给F.prototype
*/
for(var i in json){
F.prototype[i] = json[i];
}
return F;//F就是一个对象
}
 
//var Person = extend({
// aa:'aa',
// bb:'bb'
//});
var Person = com.itheima12.extend({
aa:'aa',
bb:'bb'
});
var p = new Person();
alert(p.aa);
 
闭包
在函数内部定义的函数,在外部要使用
闭包的一个使用场景:
继承的封装
匿名函数
例子:
(function(window){
function Person(){
return {
setName:setName,
getName:getName
};
}
/**
* 公开的函数
* @param {Object} name
*/
function setName(name){
this.name = name;
}
function getName(){
return this.name;
}
/**
* 私有函数
*/
function aaa(){
 
}
function bbb(){
 
}
//给window对象动态的添加了一个属性Person
window.Person = Person;
})(window);
var Person = window.Person();
Person.setName("aaa");
alert(Person.getName());
 
 
 

猜你喜欢

转载自www.cnblogs.com/SharkBin/p/8971307.html
今日推荐