Before you learn JS object-oriented programming, you first need to know what is object-oriented. Object-oriented languages have the concept of a class that allows you to create objects that have the same properties and methods. But JS does not have a class concept, so the objects in JS are different from those in other languages.
A JS object can be defined as: "A collection without attributes, whose properties can be basic values, objects, and functions." Each object is created based on a reference type.
JS creates objects in the following two ways:
1. Create an Object instance:
var person = new Object ();
2. Use object literal:
var person ={};
3. Factory mode:
function Createperson (name,age,job) { var p = new Object (); P.name=name; P.age=age; P.job=job; return p; } var P1=createperson ("Jack", "front-end Engineer"); var p2= ...;
4. Constructor Mode:
function Person (name,age,job) { this.name=name; This.age=age; This.job=job; This.sayname=function () {alert (this.name);}; } var p1= new person ("Jack", "front-end Engineer"); var p2= ...;
Here's a pause, because the constructor pattern is important, and here's an explanation: this is actually going through the following 4 steps:
(1) Create an object;
(2) Assign the constructor scope to this object (so this will point to the newly created object)
(3) Execute the code inside to add attributes to the new object;
(4) Return the new object;
The P1 and P2 created above have a constructor attribute that points to person. and P1 and P2 even if the instance of person is also an instance of object, because all objects inherit from object.
BUG: Each method is recreated on the instance, the function in JS is an object, so you can transfer the function to the outside of the constructor:
function Person (name,age,job) { this.name=name; This.age=age; This.job=job; this.sayname=sayname; } Fucntion Sayname () { alert ("THIS.name"); } var p1= ...; var p2= ...;
5. Prototype Mode:
The function we create has a prototype property, which is a pointer to an object.
JavaScript Object-Oriented programming