js中的继承与重写

本文探讨了JavaScript中的类继承机制,通过实例展示了如何创建Person和Account类,其中Account类从Person类继承并覆盖了toString()方法,实现了类的行为定制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

rt.


用function 分别定义Person和Account类模型,其中Account从Person继承,并重写toString()方法

<script type="text/javascript">
	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;
	}
</script>


end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值