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});
时间: 2024-10-10 14:16:30