Home >Web Front-end >JS Tutorial >In-depth understanding of js object-oriented
This time I will bring you an in-depth understanding of jsObject-oriented. What are the precautions for in-depth understanding of js object-oriented. The following is a practical case, let’s take a look.
Class declaration
1. Constructor
function Animal() { this.name = 'name' } // 实例化 new Animal()
2. ES6 class
class Animal { constructor() { this.name = 'name' } } // 实例化 new Animal()
1. Implement inheritance with the help of constructor
Principle: Change the this pointer of the subclass during runtime, but theproperties on the prototype chain of the parent class are not inherited, which is incomplete inheritance
function Parent() { this.name = 'Parent' } Parent.prototype.say = function(){ console.log('hello') } function Child() { Parent.call(this) this.type = 'Child' } console.log(new Parent()) console.log(new Child())
2. Implement inheritance with the help of prototype chain
Principle: Prototype chain, but if an attribute in the parent class is changed in a child class instance, the attribute in other instances will also change the child, which is also incomplete inheritancefunction Parent() { this.name = 'Parent' this.arr = [1, 2, 3] } Parent.prototype.say = function(){ console.log('hello') } function Child() { this.type = 'Child' } Child.prototype = new Parent() let s1 = new Child() let s2 = new Child() s1.arr.push(4) console.log(s1.arr, s2.arr) console.log(new Parent()) console.log(new Child()) console.log(new Child().say())
3. Constructor prototype chain
Best Practice// 父类 function Parent() { this.name = 'Parent' this.arr = [1, 2, 3] } Parent.prototype.say = function(){ console.log('hello') } // 子类 function Child() { Parent.call(this) this.type = 'Child' } // 避免父级的构造函数执行两次,共用一个 constructor // 但是无法区分实例属于哪个构造函数 // Child.prototype = Parent.prototype // 改进:创建一个中间对象,再修改子类的 constructor Child.prototype = Object.create(Parent.prototype) Child.prototype.constructor = Child // 实例化 let s1 = new Child() let s2 = new Child() let s3 = new Parent() s1.arr.push(4) console.log(s1.arr, s2.arr) // [1, 2, 3, 4] [1, 2, 3] console.log(s2.constructor) // Child console.log(s3.constructor) // Parent console.log(new Parent()) console.log(new Child()) console.log(new Child().say())I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
The above is the detailed content of In-depth understanding of js object-oriented. For more information, please follow other related articles on the PHP Chinese website!