Before learning JS object-oriented programming, you first need to know what is object-oriented. Object-oriented languages have the concept of a class that enables you to create objects that have the same properties and methods. However, JS does not have the concept of class, so the object in JS and other language objects are different.
The 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 more important, 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) Run the code inside, adding 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 at the same time, because all objects inherit from object.
BUG: Each method is created again on the instance, the function in JS is an object, so the function can be transferred 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.
6. Abstract functions:
Object.extend=function (Destination,source) {in source) {Destination[property]=source[property];} return destination;} Defines an abstract base class base, no constructor function base () {};base.prototype={ initialize:function () { this.oninit ();//calls a virtual method }} function Subclassa () {//constructor}subclassa.prototype=object.extend ({propinsubclassa: "Propinsubclassa", OnInit: function () {alert (This.propinsubclassa);}},base.prototype); function Subclassb () {//constructor}subclassb.prototype= Object.extend ({propinsubclassb: "Propinsubclassb", Oninit:function () {alert (THIS.PROPINSUBCLASSB);}}, Base.prototype); var obja=new subclassa (); obja.initialize ();//Output "Propinsubclassa" var objb=new subclassb (); O Bjb.initialize ();//Output "PROPINSUBCLASSB"
JavaScript Object-oriented programming