给类添加函数
在JavaScript 中,在构造函数中给类添加函数和给对象添加属性是一模一样的:
- Person.find = function(id){ /*...*/ };
- var person = Person.find(1);
广州网站建设,广州网站设计,广州网站制作,网站建设,网站设计,广州网站建设公司,广州网站设计公司
要想给构造函数添加实例函数,则需要用到构造函数的prototype :
- Person.prototype.breath = function(){ /*...*/ };
- var person = new Person;
- person.breath();
一种常用的模式是给类的prototype 起一个别名fn,写起来也更简单:
- PersonPerson.fn = Person.prototype;
- Person.fn.run = function(){ /*...*/ };
实际上这种模式在jQuery 的插件开发中是很常见的,将函数添加至jQuery.fn 中也就相当于添加至jQuery 的原型中。