javascript中五种方式实现方法的定义

首先我们假设我们需要一个say方法用来说一句话,一个walk方法用来表示走了一步,那么下面让我们用五种方式实现这两个方法的定义。

1.function say()

{

alert("hello world");

}

function walk()

{

alert("walk")

}

2.

var Person=function(){};

Person.propotyoe,say=function()

{

alert("hello world");

}

Person.prototype.walk=function()

{

alert("walk");

}

3.var Person={};

Person.prototype={

say:function(){

alert("hello world")

}

walk:function()

{

alert("walk");

}

}

4.

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

{

 this.protype[name]=fn;

}

var Person=function(){};

Person.method("say"function(){

alert("hello world")

})

Person.method("walk"function(){

alert("walk")

})

5.

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

{

 this.protype[name]=fn;

return this;

}

var Person=function(){};

Person.method("say"function(){

alert("hello")

}).

method("walk"function(){

alert("walk")

})

原文地址:https://www.cnblogs.com/heshan664754022/p/2250069.html