JS定义对象方法?

第一种:构造函数形式  把参数作为构造函数的参数传递,这样对于对象的初始化更灵活一点

<script language="javascript"><!--

/**定义一个animal类*/
function Animal(name){
//this.name = "Animal";

this.name = name;
this.showName = function(){ //定义方法
alert(this.name);
}
}
/**定义一个Cat类*/
function Cat(){
this.name = "Cat";
}

/**创建两个类对象*/
var animal = new Animal('monkey');
var cat = new Cat();

//通过call或apply方法,将原本属于Animal对象的showName()方法交给当前对象cat来使用了。
animal.showName.call(cat,","); //输入结果为"Cat" 
//animal.showName.apply(cat,[]);



// --></script>

方法二:临时定义了一个对象,没有复用性。

var animal={
  name:'pig',
  age:'1',
  get:function(name,age){
    alert(name);
}
}

 

posted @ 2014-09-24 11:25  ITCHN  阅读(298)  评论(0编辑  收藏  举报