JS基础学习三:对象模型

定义一个父类
function Person() {
	// Base Object
	var firstName = "Men"; // private variable

	this.getFirstName = getFirstName;

	function getFirstName() {
		return firstName;
	}
}


定义一个子类
function Student() {
	// Sub Object
	var num = "123";
	this.getNum = getNum;

	function getNum() {
		return num;
	}
}

利用prototype建立继承关系
// Establish inherit
Student.prototype = new Person();


构建一个toString函数,并扩展到原父类中
function toString() {
	var name = this.getFirstName();
	return "Name:" + name;
}

// 扩展JS对象
Person.prototype.toString = toString;


// 测试函数
function testObject() {
	var obj = new Person();

	alert(obj.getFirstName());
	alert(obj.firstName);// undefined
	alert(obj.toString());
	var student = new Student();

	alert(student.getFirstName());
	alert(student.getNum());
	alert(student.toString());
}

你可能感兴趣的:(java,prototype)