手写继承

158 阅读1分钟

<script type="text/javascript">
	//基于原型链的继承
	var Parent =function(){
		this.x=100;
	}
	var Child =function(){
		this.y=200;
	}
	Parent.prototype.getX =  function getX(){
		return this.x;
	};
	Child.prototype = new Parent();
	Child.prototype.getY =  function getY(){
		return this.y;
	}
	var c1 =new Child();
	console.log(c1)
	
	//基于call的继承
	var Parent =function(){
		this.x=100;
	};
	var Child =function(){
		Parent.call(this);
		this.y=200;
	};
	Parent.prototype.getX =  function getX(){
		return this.x;
	};
	Child.prototype.getY =  function getY(){
		return this.y;
	}
	var c1 =new Child;
	console.log(c1)
	
	//寄生组合式继承(一)
	var Parent =function(){
		this.x=100;
	};
	var Child =function(){
		Parent.call(this);
		this.y=200;
	};
	Parent.prototype.getX =  function getX(){
		return this.x;
	};
	Child.prototype.__proto__ = Parent.prototype;
	Child.prototype.getY =  function getY(){
		return this.y;
	}
	var c1 =new Child;
	console.log(c1)
	
	//寄生组合式继承(二)
	var Parent =function(){
		this.x=100;
	};
	var Child =function(){
		Parent.call(this);
		this.y=200;
	};
	Parent.prototype.getX =  function getX(){
		return this.x;
	};
	Child.prototype = Object.create(Parent.prototype);
	Child.prototype.getY =  function getY(){
		return this.y;
	}
	var c1 =new Child;
	console.log(c1)
	//ES6中的extend(三)
	class Parent{
		constructor() {
		    this.x=100;
		}
		getX(){
			return this.x;
		};
	}
	class Child extends Parent{
		constructor() {
			super()
		    this.y=200;
		}
		getY(){
			return this.y;
		};
	}
	var c1 =new Child;
	console.log(c1)
</script>

function Foo(){
	getName=function(){
		alert(1);};
	return this;
}
Foo.getName = function(){
		alert(2);}
Foo.prototype.getName = function(){
		alert(3);
}

var getName = function(){
		alert(4);
}

function getName(){
		alert(5);
}
Foo.getName();
getName();
Foo().getName();
getName();
new Foo.getName();
new Foo().getName();