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');
		}

猜你喜欢

转载自blog.csdn.net/yangxiaoyanger/article/details/79888076