The evolution of creating objects: four ways

Create an object in the form of a constructor

Disadvantages: adding attributes is too cumbersome

var obj = new Object();
        obj.name = "libai";
        obj.age = 12;

        // 添加属性繁琐 -> 字面量形式
        var obj1 = {
    
    
            name: "libai",
            age: 12
        }
        var obj2 = {
    
    
            name: "libai",
            age: 12
        }
Two function construction (factory mode)

Disadvantages: unable to distinguish the same attribute name of different functions

function createCat(name, age){
    
    
    return {
    
    
        name,
        age
    }
}
var cat1 = createCat("Tom", 12);
var cat2 = createCat("Jack", 16);

function createDog(name, age){
    
    
    return {
    
    
        name,
        age
    }
}
var dog1 = createDog("金毛", 6);
var dog2 = createDog("黑毛", 6);

Insert picture description here

Three constructor mode

Disadvantages: unable to provide shared attributes and methods for the instance, wasting memory

 function Cat(name, age){
    
    
            this.name = name;
            this.age = age;
            this.hobby = ["eat fish", "eat mouse"];
            this.skill = function (){
    
    
                console.log("爬树");
            }
        }
        var cat3 = new Cat("蓝", 12);
        var cat4 = new Cat("红", 6);

        function Dog(name, age){
    
    
            this.name = name;
            this.age = age;
        }
        var dog3 = new Dog("流浪", 12);

        console.log(cat3, dog3);
        console.log(cat3.hobby === cat4.hobby); // false
        console.log(cat3.skill === cat4.skill); // false
Four constructor + prototype

Advantages: The constructor adds private properties to the instance, and the prototype provides common properties

 function Person(name, age){
    
    
            this.name = name;
            this.age = age;
            this.hobby = [];
        }
        Person.prototype.skill = ["eat", "sleep"];
        Person.prototype.run = function (){
    
    
            console.log("run");
        }

        var zs = new Person("张三", 12);
        var lb = new Person("李白", 16);
        console.log("zs.hobby === lb.hobby", zs.hobby === lb.hobby); // false
        console.log("zs.skill === lb.skill", zs.skill === lb.skill); // true
        console.log("zs.run === lb.run", zs.run === lb.run); // true
        lb.hobby.push("drink");
        console.log(zs.hobby);

Guess you like

Origin blog.csdn.net/weixin_47067248/article/details/107993299