js构造函数传参

1.直接传参并用this关键字初始化属性

function Person(name,age,learn){

this.name = name;
this.age = age;
this.learn = learn || false;
}

Person.prototype.isWork=false;

Person.prototype.work=function(){
this.isWork=true;
};
Person.prototype.unwork = function(){
this.isWork=false;
};

//实例化类的一个对象,传递三个参数中的两个值用于初始化
var tom = new Person("tom",20);
alert(tom.name);
alert(tom.age);

 

2.用对象直接量作为构造函数的参数

function Person(defaults){
    defaults = defaults || {};
    this.name = defaults.name || null;
    this.age = defaults.age || 0;
    this.iswork = defaults.iswork || false;
}
Person.prototype.ismerry = false;
Person.prototype.merry = function(){
    this.ismerry = true;
};
Person.prototype.unmerry = function(){
    this.ismerry = false;
};
var tom = new Person({nam:"tom",age:22});

 

posted @ 2016-12-24 17:34  行动派  阅读(2399)  评论(0编辑  收藏  举报