关于javascript:JS的封装JS插件的封装

5次阅读

共计 1537 个字符,预计需要花费 4 分钟才能阅读完成。

JS 中类的概念

类,实际上就是一个 function,同时也是这个类的构造方法,new 创立该类的实例,new 出的对象有属性有办法。
办法也是一种非凡的对象。

类的办法

在构造方法中初始化实例的办法(就是在构造方法中间接编写办法,并 new 实例化)是不举荐的,耗费内存(每次实例化的时候都是反复的内容,多占用一些内存,既不环保,也不足效率)。
所有实例是共有的,创立多个实例不会产生新的 function,举荐在类的 prototype 中定义实例的办法,
prototype 中的办法会被所有实例专用。

1. 仿照 jQuery 封装类
匿名函数

(function () {//})();

var Id = function (i) {this.id = document.getElementById(i);
};
window.$ = function (i) {return new Id(i);
};

console.log($('main'));
function Cat(name, color) {
  this.name = name;
  this.color = color;
}

var cat1 = new Cat('大毛', '黄色');
var cat2 = new Cat('二毛', '彩色');

Cat.prototype.a = 'aaa';
Cat.prototype.type = '猫科动物';
Cat.prototype.eat = function () {alert('吃老鼠');
};

cat1.eat();
cat2.eat();

console.log(cat1.name);
console.log(cat2.color);

// cat1 和 cat2 会主动含有一个 constructor 属性,指向它们的构造函数。console.log(cat1.constructor == Cat);
console.log(cat2.constructor == Cat);

// Javascript 还提供了一个 instanceof 运算符,验证原型对象与实例对象之间的关系。console.log(cat1 instanceof Cat);
try {console.log(a instanceof Cat);
} catch (e) {console.log(e);
}

所谓 ” 构造函数 ”,其实就是一个一般函数,然而外部应用了 this 变量。对构造函数应用 new 运算符,就能生成实例,并且 this 变量会绑定在实例对象上。
Javascript 规定,每一个构造函数都有一个 prototype 属性,指向另一个对象。这个对象的所有属性和办法,都会被构造函数的实例继承。

prototype 模式的验证办法
1. isPrototypeOf() 判断某个 prototype 对象和某个实例之间的关系
2. hasOwnProperty() 判断一个属性是本地属性还是继承自 prototype 对象的属性
3. in 判断是否在某个对象里

function Cat(name, color) {
  this.name = name;
  this.color = color;
}

Cat.prototype.type = '猫科动物';

var cat1 = new Cat('大毛', '黄色');
var cat2 = new Cat('二毛', '彩色');

console.log(Cat.prototype.isPrototypeOf(cat1));
console.log(Cat.prototype.isPrototypeOf(cat2));

console.log(cat1.hasOwnProperty('name'));
console.log(cat2.hasOwnProperty('type'));

console.log('name' in cat1);
console.log('type' in cat1);
正文完
 0