码迷,mamicode.com
首页 > Web开发 > 详细

js构造函数传参

时间:2016-12-24 20:24:44      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:name   his   this   als   对象   alert   null   blog   false   

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});

 

js构造函数传参

标签:name   his   this   als   对象   alert   null   blog   false   

原文地址:http://www.cnblogs.com/littlewriter/p/6217972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!