现在的位置: 首页 > 综合 > 正文

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

2013年04月03日 ⁄ 综合 ⁄ 共 741字 ⁄ 字号 评论关闭

首先我们假设我们需要一个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")

})

抱歉!评论已关闭.