代码改变世界

javascript面向对象起步

2011-09-06 21:31  小sa  阅读(196)  评论(0编辑  收藏  举报

注:console.log("")只能在Firefox,或 chrome 中firebug调试其他地方请换成 alert("")

/* 起步之一直接写成函数 此时为面向过程 */

function startAnimalation() {

console.log(
"start");

}

function stopAnimalation() {

console.log(
"stop");

}

/* 起步之二*/

var Animal
= function() {

console.log(
"constructor");

};

Animal.prototype.start
= function() {

console.log(
"start");

};

Animal.prototype.stop
= function() {

console.log(
"");

};

/* 用法 */

var myAnimal
= new Animal();

myAnimal.start();

myAnimal.stop();

/* 起步之三 方法直接打包到prototype */

var Animal
= function() {

console.log(
"constructor");

};

Animal.prototype
= {

start: function() {

console.log(
"start");

},

stop: function() {

console.log(
"stop");

}

};

/* 起步之四 拓展Function方法 可以动态添加 方法或属性 到prototype之中*/

Function.prototype.method
= function(name, fn) {

this.prototype[name] = fn;

};

var Animal
= function() {

console.log(
"");

};

Animal.method(
'start', function() {

console.log(
"");

});

Animal.method(
'stop', function() {

console.log(
"");

});

/* 起步之五 支持“.” 拓展 */

Function.prototype.method
= function(name, fn) {

this.prototype[name] = fn;

return this;

};

var Animal
= function() {

console.log(
"");

};

Animal. method(
'start', function() {console.log("");}). method('stop', function() {console.log(""); });