current position:Home>Object oriented JavaScript
Object oriented JavaScript
2022-04-29 08:09:21【Chen Chen is trying】
3、 ... and 、 Object oriented advanced
This section requires you to look ahead Advanced function 1、 Prototype and prototype chain Familiar with , If you don't master it well enough, it will be relatively difficult to understand
1、 Object creation pattern
Ⅰ-Object Constructor Pattern
Mode one : Object Constructor Pattern
- tricks : Create empty first Object object , Then dynamically add attributes / Method
- Applicable scenario : At the beginning, the internal data of the object is uncertain
- problem : Too many sentences
/* A person : name:"Tom", age: 12*/ // Create empty first Object object var p = new Object() p = { } // At this time, the internal data is uncertain // Then dynamically add attributes / Method p.name = 'Tom' p.age = 12 p.setName = function (name) { this.name = name } // test console.log(p.name, p.age) p.setName('Bob') console.log(p.name, p.age)
Ⅱ- Object literal pattern
Mode two : Object literal pattern
- tricks : Use {} Create objects , Also specify the properties / Method
- Applicable scenario : At the beginning, the internal data of the object is determined
- problem : If you create multiple objects , There are duplicate codes
// Object literal pattern var p = { name: 'Tom', age: 12, setName: function (name) { this.name = name } } // test console.log(p.name, p.age) p.setName('JACK') console.log(p.name, p.age) var p2 = { // If you create multiple objects, the code is repetitive name: 'Bob', age: 13, setName: function (name) { this.name = name } }
Ⅲ- Factory mode
Mode three : Factory mode
- tricks : Create objects dynamically through factory functions and return
- Applicable scenario : Multiple objects need to be created
- problem :
Object does not have a specific type
, All are Object type// Function that returns an object ===> Factory function function createPerson(name, age) { var obj = { name: name, age: age, setName: function (name) { this.name = name } } return obj } // establish 2 personal var p1 = createPerson('Tom', 12) var p2 = createPerson('Bob', 13) // p1/p2 yes Object type function createStudent(name, price) { var obj = { name: name, price: price } return obj } var s = createStudent(' Zhang San ', 12000) // s It's also Object
Ⅳ- Custom constructor mode
Mode 4 : Custom constructor mode
- tricks : Custom constructors , adopt new Create objects
- Applicable scenario : More than one... Needs to be created
Type determination
The object of , Compared with the factory mode above- problem : Each object has the same data , Waste of memory
// Definition type function Person(name, age) { this.name = name this.age = age this.setName = function (name) { this.name = name } } var p1 = new Person('Tom', 12) p1.setName('Jack') console.log(p1.name, p1.age) console.log(p1 instanceof Person) function Student(name, price) { this.name = name this.price = price } var s = new Student('Bob', 13000) console.log(s instanceof Student) var p2 = new Person('JACK', 23) console.log(p1, p2)
Ⅴ- Constructors + Combination mode of prototype
Methods five : Constructors + Combination mode of prototype –>
It's best to write in this way
- tricks : Custom constructors , Property is initialized in a function , Method is added to the prototype
- Applicable scenario : need
Create multiple types to determine
The object of- Put it on the prototype to save space ( Just load the method once )
// Only general functions are initialized in the constructor function Person(name, age) { this.name = name this.age = age } Person.prototype.setName = function (name) { this.name = name } var p1 = new Person('Tom', 23) var p2 = new Person('Jack', 24) console.log(p1, p2)
2、 Inheritance pattern
Ⅰ- Prototype chain inheritance
The way 1: Prototype chain inheritance
- tricks
- Define the parent type constructor
- Add a method to the prototype of the parent type
- Defines the constructor for subtypes
- Create an object of the parent type and assign it to the prototype of the child type
Set the construction property of the subtype prototype to subtype
–> If you have doubts here, you can see this note Advanced function 1、 Prototype and prototype chain- Add methods to subtype prototypes
- Create sub type objects : You can call methods of the parent type
- The key
The prototype of the subtype is an instance object of the parent type
// Parent type function Supper() { this.supProp = ' Father's prototype chain ' } // Add a... To the prototype of the parent type [showSupperProp] Method , Print itself subProp Supper.prototype.showSupperProp = function () { console.log(this.supProp) } // subtypes function Sub() { this.subProp = ' Son's prototype chain ' } // The prototype of the subtype is an instance object of the parent type Sub.prototype = new Supper() // Let the prototype of the subtype constructor Point to subtypes // If not , Its constructor is not found [`new Supper()`] From the top when Object Inherited constructor , Point to [`Supper()`] Sub.prototype.constructor = Sub // Add a... To the prototype of the subtype [showSubProp] Method , Print itself subProp Sub.prototype.showSubProp = function () { console.log(this.subProp) } var sub = new Sub() sub.showSupperProp() // Father's prototype chain sub.showSubProp() // Son's prototype chain console.log(sub) /** Sub {subProp: " Son's prototype chain "} subProp: " Son's prototype chain " __proto__: Supper constructor: ƒ Sub() showSubProp: ƒ () supProp: " Father's prototype chain " __proto__: Object */
① figure
Be careful
: Not shown in this figure [constructor Constructors
], It will be pointed out in the supplement below
② Constructors complement
For code [
Sub.prototype.constructor = Sub
] Is there any doubt ?If not , Its constructor is not found [
new Supper()
] It's from the top Object Inherited constructor , Point to [Supper()
], Although if you don't add this sentence , In general, the use is unaffected , But you have an attribute pointing to the wrong , If you are in a large project, where can you call it again ?
- Here we can add constructor The concept of :
constructor We call it constructors , Because it points back to the constructor itself
- Its function is to make a constructor produce All instance objects ( such as f) Can find his constructor ( such as Fun), Usage is f.constructor
- There is no in the instance object at this time constructor This attribute , So I found it up the prototype chain Fun.prototype Inside constructor, And point to Fun The function itself
- constructor This exists in the prototype , Pointing constructor , When you become a child , If... In the prototype chain constructor Not in itself, but in the parent prototype , So the constructor pointing to the parent class
- Because the inheritance here directly changes the constructor prototype The direction of , So in sub In the prototype chain of ,Sub.prototype No, constructor attribute , Instead, I saw a super example
- This makes sub Example of constructor Can't use . So he can use , Right there super An example is added manually constructor attribute , And point to Sub The function sees a super example
Ⅱ- Inheritance by borrowing the constructor ( fake )
The way 2: Inheritance by borrowing the constructor ( fake )
- tricks :
- Define the parent type constructor
- Define a subtype constructor
- Calling parent type constructor in subtype constructor
- The key :
Common in subtype constructors call() Call the parent type constructor
- effect :
- Can borrow the constructor in the parent class , But not flexible
function Person(name, age) { this.name = name this.age = age } function Student(name, age, price) { // Use here call(), take [Student] Of this Pass to Person Constructors Person.call(this, name, age) // amount to : this.Person(name, age) /*this.name = name this.age = age*/ this.price = price } var s = new Student('Tom', 20, 14000) console.log(s.name, s.age, s.price)
[
Person
] Medium this It's dynamic , stay [Student
] In the use of [Person.call(this, name, age)
] Changed its this Point to , So this effect can be achieved
Ⅲ- Combination inheritance
The way 3: Prototype chain + Borrowing the combination inheritance of constructors
- Using prototype chain to realize method inheritance of parent type object
- utilize super() Borrowing the parent type build function to initialize the same property
function Person(name, age) { this.name = name this.age = age } Person.prototype.setName = function (name) { this.name = name } function Student(name, age, price) { Person.call(this, name, age) // To get properties this.price = price } Student.prototype = new Person() // In order to see the methods of the parent type Student.prototype.constructor = Student // correct constructor attribute Student.prototype.setPrice = function (price) { this.price = price } var s = new Student('Tom', 24, 15000) s.setName('Bob') s.setPrice(16000) console.log(s.name, s.age, s.price)
copyright notice
author[Chen Chen is trying],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290809166587.html
The sidebar is recommended
- Which one charges less for opening a securities account and how to open the account
- Spring MVC notes 02 domain object sharing data, view, restful, httpmessageconverter, file upload and download
- Httpclient setting timeout
- Command line / Python uses pdf2htmlex to convert PDF to HTML
- [front end three swordsmen III] analysis of JavaScript scalpel Part II
- How to choose the front-end learning path
- Finite element parametric element, calculation, theoretical problems
- Handwritten CSS modules to understand its principle
- Front end browser debugging tips
- Performance problem analysis guide for enterprise JavaScript applications running in production systems
guess what you like
CSS aspect-ratio All In One
Actual combat of vue3 project --- Zhihu daily --- details page
Actual combat of vue3 project --- Zhihu daily --- home page function
Great Wall Motors is falling endlessly! The boss has lost 150 billion yuan in half a year, and the performance of the new energy sector has improved
Nginx tips batch shutdown process
Openresty introduces nginx_ upstream_ check_ Module module
Nginx multiple servers_ How does name match
Why does the front end still prompt cannot post, and the error reported by the back end still prompt null pointer?
HTML Li set margin: 50%, but the width of the outermost div is the standard
Are there any specific steps to create a prototype, such as JavaScript?
Random recommended
- How does HTML5 display the value obtained from the database in the specified area
- Problems related to nginx rewriting interface
- What happens when you open a CSS file in eclipse without responding
- React download local template can be downloaded locally, but the deployment online download is blank
- @Babel / traverse official example running error: typeerror: traverse is not a function
- The click event of jQuery has no effect
- How to learn from non professional background?
- Usage of API documented as @since 1.8+ less... (Ctrl+F1) Inspection info: This inspection finds all
- Configuration Vue of webpack
- Introduction to nginx (learning notes)
- Is the financial management class of qiniu school true? Can you learn how to manage money in free lessons
- How does Java randomly get elements from a list
- Use of Vue on in Vue
- Use of Vue router
- Vue basic syntax
- Use of webpack
- Vue diff algorithm
- CSS -- Text gradient from top to bottom
- Routing: Vue router
- Leetcode 658. Find K closest elements
- How to configure Vue in Vue project config. JS to solve cross domain problems
- Centos6 makes nginx-1.21.6-rpm package -- the way to build a dream
- [vue2-sgg v] vuex
- [vue2-sgg vi] route Vue router guard
- [vue2-sgg VII] Vue export and deploy to nginx --- UI component library (element UI...)
- Chapter 12 Ajax
- Clion remote debugging ubutun server, blood lessons
- The latest vue-i18n international plug-in realizes language switching (with source code)
- Vue monitors watch usage
- Vue encapsulates Axios to the full version of the calling interface (code source code)
- Watch data monitoring in Vue and detailed explanation of various attributes in watch
- Vue encapsulates Axios to call interface Full Version (code source code) latest recommendation (II)
- Vue encapsulates Axios to the full version of the calling interface (code source code)
- Ajax usage based on JQ
- Vue project optimization
- Vue - form generator form code generation
- Data acquisition in vuex is assigned to the local problem, and when is vuex data assigned to the local problem
- The modal box component is encapsulated in Vue, and the animation effect in Vue
- Swiper, the application of swiper in Vue, and various versions of swiper are applied in Vue projects
- Python——ReadTimeoutError: HTTPSConnectionPool(host=‘files.pythonhosted.org‘, port=443)