天天看點

javascript(二) JavaScript之建立類

//定義一個類
var Person = function(name,age){
	this.name=name;
	this.age=age;
	var _sex = '男';
	this.getSex = function(){
		return _sex;
	};
	this.setSex = function(sex){
		this._sex=sex;
	};
};

//增加屬性、方法
//第一種:
/*
Person.prototype.id=10;
Person.prototype.method=function(){
	alert(this.age);
};
*/

//第二種:采用
Person.prototype={
	constructor:Person,
	id:10,
	method:function(){
		alert('method...');
	}
};

var p = new Person('張三',30);
alert(p.name);
alert(p.getSex());
alert(p.id);
p.method();
           

繼續閱讀