javascript 对象都有一个prototype属性,prototype 主要用在为对象动态增加属性。总结了一下常见使用方式!
1.直接修改对象属性
var Anim = function () {
}
Anim.prototype.start = function () {
console.log("start");
}
Anim.prototype.stop = function () {
console.log("stop");
}
使用方式
var myAnim = new Anim();
myAnim.start();
myAnim.stop();
2.通过配置(setting)的形式
使用过ExtJs的童鞋肯定知道,组件通常有一个配置对象。
var Anim = function () {
}
Anim.prototype = {
start: function () {
console.log("start1");
},
stop: function () {
console.log("stop1");
}
};
使用方式同上
3.先声明后定义式
记得jquery里面的bind方法吗?通常是$("#id").bind("click",function(){});这种形式出现在世人面前,那这是如何做到的呢?
Function.prototype.method = function (name, fn) {
this.prototype[name] = fn;
return this;
}
Anim.method("start", function () {
console.log("start")
});
Anim.method("stop", function () {
console.log("stop")
});
使用方法同上,是不是觉得一模一样的?
注意:上述方式可以采用链式编程(想起jquery里面的链式编程了嘛?)
Anim.
method("start", function () {
console.log("start")
}).
method("stop", function () {
console.log("stop")
});
使用方式亦同上!
4.即声明即用
(function (a, b) { alert(a * b); })(3, 4);
5.实例专有属性
var myAnim = new Anim();
myAnim.start();
myAnim.stop();
myAnim.display = function () {
console.log("display");
}
myAnim.display();
var hisAnim = new Anim();
hisAnim.display();