Let’s look at the inheritance of JS classes first
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | <!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8" >
<title>JS类的继承</title>
</head>
<body>
<script type= "text/javascript" >
var Animal = function (name) {
this.name = name;
}
Animal.prototype.Eat = function () {
console.log(this.name + " Eat" );
};
var a = new Animal( "Animal" );
var Cat = function (name, sex) {
Animal.call(this, name);
this.sex = sex;
}
Cat.prototype = new Animal();
console.log(Cat.prototype.constructor);
Cat.prototype.constructor = Cat;
console.log(Cat.prototype.constructor);
Cat.prototype.getSex = function () {
return this.sex;
}
var _m = new Cat( 'cat' , 'male' );
console.log(_m.getSex());
console.log(_m.Eat());
</script>
</body>
</html>
|
Copy after login
Let’s look at JS prototypal inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8" >
<title>JS原型继承</title>
</head>
<body>
<!--原型继承-->
<script type= "text/javascript" >
var clone = function (obj) {
var _f = function () {};
_f.prototype = obj;
return new _f;
}
var Animal = {
somthing: 'apple' ,
eat: function () {
console.log( "eat " + this.somthing);
}
}
var Cat = clone (Animal);
console.log(Cat.eat());
Cat.somthing = 'orange' ;
console.log(Cat.eat());
var Someone = clone (Cat);
</script>
</body>
</html>
|
Copy after login
We can try it out. JS class inheritance children.constructor==father returns true, while prototypal inheritance children.constructor==father returns false;
The above brief analysis of JS prototype inheritance and class inheritance is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home more.