js object-oriented knowledge is the most basic entry-level knowledge point. The following is a detailed introduction to js object-oriented knowledge through the example code of this article. Friends who are interested can learn together
Class Declaration
1. Constructor
##
function Animal() { this.name = 'name' } // 实例化 new Animal()
2. ES6 class
class Animal { constructor() { this.name = 'name' } } // 实例化 new Animal()
Class inheritance
1. Implement inheritance with the help of constructor
Principle: Change the this pointer of the subclass when running, but the attributes on the prototype chain of the parent class are not inherited, which is incomplete inheritancefunction 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 subclass instance, the attribute in other instances will also change the subclass. , it 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())
The above is the detailed content of A first introduction to object-oriented JavaScript. For more information, please follow other related articles on the PHP Chinese website!