JS继承的方法一

1、原型链继承(prototype)

<!DOCTYPE html>
<html>
<body>
<script>
function A(name){
		this.name = name;
		this.sleep = function(){
			console.log(this.name+"正在睡觉...");
		}
		this.eat = function(food){
			console.log(this.name+"正在吃:"+food);
		}
	}

function C(name){
		this.name = name;
	}

	C.prototype = new A();

	var c = new C("Toms");

	console.log(c.name); //Toms
	console.log(c.eat('水果')); //Toms正在吃:水果
	console.log(c.sleep()); //Toms正在睡觉...
</script>
</body>
</html>

创建一个A类,给它一个名字属性,一个睡觉的方法,一个吃的方法

创建一个C类,给它一个名字属性

利用prototype确立继承关系,但是这种方法有个缺点,new出来的对象会大量的占内存空间,所以使用另一种方法Object.create来确立继承关系

function Parent(){}

Parent.prototype.age = 18;

function Child(){}

Child.prototype = Object.create(Parent.prototype); //确定继承关系
Child.prototype.constructor = Child;//改回原来对象(Child)的构造器
//只要某个构造器的prototype改变,新new出的对象的构造器也会改变
Child.prototype.cno = "01"; var p = new Parent(); var c = new Child(); console.log(c.age);

  

2.构造继承(call)

//*********call的理解*********
//this指向谁是由运行时决定
//this等于.号左边的东西
function P(name,age){
	this.name = name;
	this.age = age;
}

var o = {};
P.call(o,"a",18); //此时P函数里面的this等于第一个参数
console.log(o.name);
console.log(o.age);

  

<!DOCTYPE html>
<html>
<body>
<script>
function A(name){
		this.name = name;
		this.sleep = function(){
			console.log(this.name+"正在睡觉...");
		}
		this.eat = function(food){
			console.log(this.name+"正在吃:"+food);
		}
	}

function B(name){
		A.call(this);
		this.name = name;
	}

	var b = new B("Lucy");

	console.log(b.name); //Lucy
	console.log(b.eat('零食')); //Lucy正在吃:零食
	console.log(b.sleep()); //Lucy正在睡觉...
</script>
</body>
</html>

  总得来说JS里的类就是构造器+原型

  且constructor构造器一般指向函数。

原文地址:https://www.cnblogs.com/-1212huan/p/7918625.html