js实现继承的5种方式,

转自js继承5种方式

1、对象冒充

		// 对象冒充
		function Parent(username) {
			this.username = username;
			this.hello = function () {
				alert("hello");
			}
		}

		function Child(username, password) {
			this.method = Parent;  // 将临时属性指向Parent所指向的队形
			this.method(username);  // 执行Parent所指向的对象函数
			delete this.method; // 销毁临时属性,此时Child已经拥有了parent的所有属性和方法
			this.password = password;
			this.world = function () {
				alert('world');
			}
		}
		var parent = new Parent();
		var child = new Child();
		parent.hello();
		child.hello();


2、call或者apply

		// call和apply继承
		function Parent2(username) {
			this.username = username;
			this.hello = function () {
				alert("hello");
			}
		}
		function Child2(username, password) {
			Parent2.call(this, username);  // call方法
			this.world = function () {
				alert('world');
			}
		}
		function Child3(username, password) {
			Parent2.apply(this, new Array(username));  // apply方法
			this.world = function () {
				alert('world');
			}
		}

3、原型链继承

		// 原型方法
		function Parent4() {
		}
		Parent4.prototype.hello = 'hello';
		Parent4.prototype.sayHello = function () {
			alert('hello');
		}
		function Child4() {
		}
		Child4.prototype = new Parent4();
		Child4.prototype.world = 'world';
		Child4.prototype.sayWorld = function () {
			alert('world');
		}

4、混合式继承

// 混合式继承
		function Parent5(username) {
			this.username = username;
		}
		Parent5.prototype.sayHello = function () {
			alert('hello');
		}
		function Child5(username) {
			Parent5.call(this, username);
			this.world = 'world';
		}
		Child5.prototype = new Parent5();
		Child5.prototype.sayWorld = function () {
			alert('sayWorld');
		}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值