jsの継承と書き換え


ト.
PersonとAcceountのモデルはそれぞれFunctionで定義され、AcceountはPersonから継承され、toString()の方法を書き換える.

	function go() {
		var acc1 = new Account('Taro', 'Shibuya1-1-2', '1001', 20000);
		var acc2 = new Account('Hanako', 'Akasaka2-3-4', '1002', 35000);
		acc1.toString();
		acc2.toString();
	}

	//   Person   
	function Person(name, address) {
		this.name = name;
		this.address = address;
	}

	//  Person.property   toString  
	Person.prototype.toString = function() {
		document.write(this.name + " " + this.address + "<br>");
	}

	//   Account   
	function Account(name, address, number, amount) {
		//  Person  
		this.newObj = Person;
		this.newObj(name, address);
		delete this.newObj;

		// Account    
		this.number = number;
		this.amount = amount;
	}

	Account.prototype = Object.create(Person.prototype);
	//   "constructor"     Account
	Account.prototype.constructor = Account;

	//   Person toString  
	Account.prototype.toString = function() {
		document.write(this.name + "  " + this.address
				+ "  " + this.amount + "<br>");
	}

	Account.prototype.deposit = function(x) {
		this.amount += x;
	}

	Account.prototype.withdraw = function(x) {
		this.amount -= x;
	}
end.