js object oriented

Object-oriented programming is to create a programming model based on the real-world model in an abstract way, mainly including several techniques of modularization, polymorphism, and encapsulation. For JavaScript, its core is to support object-oriented, and it also provides powerful and flexible prototype-based object-oriented programming capabilities.
1. Understanding the object: 
(1) Based on the Object object 
var person = new Object(); 
person.name = 'Wang'; 
person.age = 20; 
person.getName = function(){ 
    return this.name; 

(2) Object literal method 
var person = { 
    name : 'Wang', 
    age : 20, 
    getName : function(){ 
        return this.name; 
    } 

Second, create an object 
(1) factory pattern 
function createPerson(name, age, job) { 
    var oo = new Object(); 
    oo.name = name; 
    oo.age = age; 
    oo.job = job; 
    oo.getName = function () { 
        return this.name; 
    } 
    return o;//Use return to return the generated object instance 

var person = createPerson('Jack', 19, 'Worker'); 
Create an object and hand it over to a factory method for implementation, you can pass parameters, but The main disadvantage is that the object type cannot be recognized, because object creation is done using Object's native constructor. 

(2) Constructor mode 
function Person(name,age,job){ 
    this.name = name; 
    this.age = age; 
    this.job = job; 
    this.getName = function () { 
        return this.name; 
    } 

var person1 = new Person('Bob', 18, 'Driver'); 

var person2 = new Person('Janny', 22, 'Waiter'); 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326539044&siteId=291194637