您的位置:首页 > Web前端 > JavaScript

js面向对象编程,定义类的四种方法

2014-03-12 14:41 239 查看
 

  第一种定义类的方法:

/* Anim class. */

var Anim = function() {
...
};
Anim.prototype.start = function() {
...
};
Anim.prototype.stop = function() {
...
};

/* Usage. */

var myAnim = new Anim();
myAnim.start();
...
myAnim.stop();


第二种定义类的方法:

/* Anim class, with a slightly different syntax for declaring methods. */

var Anim = function() {
...
};
Anim.prototype = {
start: function() {
...
},
stop: function() {
...
}
};


第三种方法:

/* Add a method to the Function class that can be used to declare methods. */

Function.prototype.method = function(name, fn) {
this.prototype[name] = fn;
};

/* Anim class, with methods created using a convenience method. */

var Anim = function() {
...
};
Anim.method('start', function() {
...
});
Anim.method('stop', function() {
...
});


第四种方法:

/* This version allows the calls to be chained. */

Function.prototype.method = function(name, fn) {
this.prototype[name] = fn;
return this;
};

/* Anim class, with methods created using a convenience method and chaining. */

var Anim = function() {
...
};
Anim.
method('start', function() {
...
}).
method('stop', function() {
...
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: