Home > Web Front-end > JS Tutorial > body text

9 ways to create objects in JavaScript

炎欲天舞
Release: 2017-08-04 11:59:02
Original
1109 people have browsed it

———————————————————————————————————— ——————————————

Create object

label

Quasi-object mode

"use strict";
// *****************************************************************var person = new Object();
person.name = "Nicholas";
person.age = 29;
person.job = "Software Engineer";
person.sayName = function(){alert(this.name);};
Copy after login

Literal form


"use strict";
// *****************************************************************var person = {
    name: "Nicholas",
    age: 29,
    job: "Software Engineer",
    sayName: function(){alert(this.name);}
};
Copy after login

Factory Mode

  • The process of creating specific objects is abstracted, and functions are used to encapsulate the details of creating objects with specific interfaces

  • Advantages: Can create similar objects repeatedly

  • ##Disadvantages: Unable to perform object recognition

    <>

##

"use strict";
// 工厂模式
function createPerson(name, age, job) {    
    var o = new Object();
    o.name = name;
    o.age = age;
    o.job = job;
    o.sayName = function() {
        console.log(this.name);
    }    
    return o;
}
var person1 = createPerson("name1", 1, "hehe");
console.log(person1);
Copy after login

Constructor Pattern

  • Advantages:

    Can solve the problem of unavailable objects in the factory Identify the problem

    Create the object without display, directly assign the properties and methods to the

    this object, without returnStatement

  • Disadvantages:

    In the case, each

    Person objects contain the essence of a different Function instance. Creating functions in this way will result in different scope chains and Identifier resolution, but the mechanism for creating new instances of Function remains the same. And if the method is placed in the global scope, the custom reference type has no encapsulation at all

  • Through

    newKeywords to create a custom constructor

  • Creating a custom constructor means that instances of it can be identified as a trait in the future The type of

  • The constructor defined in this method is

    # defined in the Global object

  • ##Actual steps for calling the constructor:
    • Create a new object
    • Assign the scope of the constructor to the new object (
    • this points to the object)

    • Execute the code in the constructor (add properties to the new object)
    • Return the new object
"use strict";
// 构造函数模式
function Person(name, age, job) {    
    this.name = name;    
    this.age = age;    
    this.job = job;    
    this.sayName = function() {
        console.log(this.name);
    }
}
var person1 = new Person("name2", 2, "hehe");
console.log(person1);
// 检测对象类型
console.log(person1.constructor == Object); // false
console.log(person1.constructor == Person); // true
console.log(person1 instanceof Object); // true
console.log(person1 instanceof Person); // true
// 当作构造函数使用
var person2 = new Person("name3", 3, "hehe");
person2.sayName();
// 作为普通函数调用
// Person("name4", 4, "hehe"); 
// 添加到window,严格模式下无法访问
// window.sayName(); 
// name4
// 在另一个对象的作用域中调用
var o = new Object();
Person.call(o, "name5", 5, "111"); // 在对象o中调用
o.sayName(); // o就拥有了所有属性和sayName()方法
// 创建两个完成同样任务的Function实例是没必要的,有this对象在,不需要在执行代码前就把函数绑定到特定对象上面
console.log(person1.sayName == person2.sayName); // false,但方法是相同的
// 通过把函数定义转移到构造函数外来解决
function Person2(name, age, job) {    
    this.name = name;    
    this.age = age;    
    this.job = job;    
    this.sayName = sayName2;
}
function sayName2() { // 在这种情况下person1和person2共享同一个全局函数
    console.log(this.name);
}
var person1 = new Person2("name6", 6, "hehe");
var person2 = new Person2("name7", 7, "hehe");
console.log(person1.sayName == person2.sayName); // true
Copy after login


Prototype pattern

  • Advantages:

    Can solve the problem of constructor pattern creating multiple method instances

    All object instances can share the properties and methods contained in the prototype. It is not necessary to define the information of the object instance in the constructor, but the information can be added directly to the prototype object

  • Disadvantages:

    All properties in the prototype are shared by many instances, for containing references For attributes of type values ​​(arrays, etc.), this is (a big problem)

    The link of passing initialization parameters to the constructor is omitted. As a result, all instances are by default The same attribute value will be obtained, and parameters need to be passed in separately (this should not be a problem)

    So few people use the prototype mode alone, see the comprehensive use below

  • Every function we create has a prototype (prototype) attribute, which is a pointer to Pointer to the object.

  • Understanding of prototypes:

    Any time a new function is created, it will be based on a specific set of rules Create a prototype attribute for the function, which points to the prototype object of the function.

    By default, all prototype objects will get a constructor (constructor) attribute, containing a pointer to prototypeProperty pointer

    In the instance, Person.prototype.constructor Person, you can continue to add other properties and methods to the prototype object through the constructor

    After creating a custom constructor, the prototype object only obtains# by default ##constructor attributes, other methods are inherited from Object, the prototype pointer is called [[prototype]], but no access method is provided in the script. This attribute is not visible in other implementations, but the browser adds a _proto_ attribute to the object.

    The connection of the prototype pointer exists between the instance and the prototype object of the constructor, not between the instance and the constructor .

    Illustration:

  • ## About the properties of the prototype:

    Instance:

    person1, prototype: Person

    When searching for attributes, first check whether the attributes in

    person1 have name, and if so, return ## The value of #person1.name, if not, check if there is name in the prototype Person, refer to the prototype The difference between the structure of chain and object

    ##in
  • operator and

    hasOwnProperty():

    in操作符:无论属性是在实例还是原型中,都返回true,只有在不存在的情况下才会false

    hasOwnProperty(): 只有在调用的实例或原型中的属性才会返回true

  • 案例中整个重写原型的问题图解:

    <>


"use strict";
// *****************************************************************
// 原型模式
function Person() {};
Person.prototype.id = 0;
Person.prototype.name = "name0";
Person.prototype.sayName = function() {
    console.log(this.name);
};

var person1 = new Person();
person1.sayName();
var person2 = new Person();
person2.name = "name2";
person2.sayName();
console.log(person1.sayName == person2.sayName);
Person.prototype.name = "111"; // 对原型中的初始值修改后,所有的子实例都会修改初始值
person1.sayName();
person2.name = "222";
person2.sayName();
delete person2.name; // 删除person2.name
person2.sayName(); // 111,来自原型

// *****************************************************************
// isPrototypeOf():确定原型关系的方法
console.log(Person.prototype.isPrototypeOf(person1)); // true
var person3 = new Object();
console.log(Person.prototype.isPrototypeOf(person3)); // false
// getPrototypeOf():返回原型[[prototype]]属性的方法
// in操作符
console.log(Object.getPrototypeOf(person2)); // 包含Person.prototype的对象
console.log(Object.getPrototypeOf(person2) == Person.prototype); // true
console.log(Object.getPrototypeOf(person2).name); // 111,初始值

// hasOwnProperty():检测一个属性是唉实例中还是在原型中
console.log(Person.hasOwnProperty("name")); // true
console.log(person1.hasOwnProperty("name")); // false 在上面的操作中没有为person1添加name
console.log("name" in person1); // true
person2.name = "333";
console.log(person2.hasOwnProperty("name")); // true
console.log("name" in person2); // true

// p.s.Object.getOwnPropertyDescriptor()方法必须作用于原型对象上
console.log(Object.getOwnPropertyDescriptor(person1, &#39;name&#39;)); // undefined
console.log(Object.getOwnPropertyDescriptor(Person, &#39;name&#39;)); // Object{...}

// *****************************************************************
// 简单写法
// 以对象字面量的形式来创建新的对象原型
// p.s.此时constructor属性不再指向Person,而是指向Object,因为此处重写了整个对象原型
function Per() {};
Per.prototype = {
    id: 0,
    name: "Per_name",
    sayName: function() {
        console.log(this.name);
    }
}
// 在该写法中要重写constructor属性,如果直接重写constructor属性会导致[[Enumberable]]=true,可枚举,原生的constructor属性不可枚举
// 正确的重写方法
Object.defineProperty(Per.prototype, "constructor", { enumberable: false, value : Per });
var per1 = new Per();
console.log(person1.constructor); // Person()
console.log(per1.constructor); // Per(),如果不加constructor:Per返回Obejct()

// 图解见上部
// 如果直接重写整个原型对象,然后在调用per1.sayName时候会发生错误,因为per1指向的原型中不包含以改名字明明的属性,而且整个重写的对象无法修改
// function Per() {};
// var per1 = new Per();
// Per.prototype = {
//     constructor:Per,
//     id: 0,
//     name: "Per_name",
//     sayName: function() {
//         console.log(this.name);
//     }
// }
// var per2 = new Per();
// per1.sayName(); 
// error
// per2.sayName(); 
// Per_name
// *****************************************************************
// 问题
// 对一个实例的数组进行操作时,其他所有实例都会跟随变化
function Per2() {};
Per2.prototype = {
    constructor:Per2,
    id: 0,
    name: "Per_name",
    arr : [1,2]
}
var per3 = new Per2();
var per4 = new Per2();
console.log(per3.arr); // [1, 2]
console.log(per4.arr); // [1, 2]
per3.arr.push("aaa");
console.log(per3.arr); // [1, 2, "aaa"]
console.log(per4.arr); // [1, 2, "aaa"]
console.log(per3.arr === per4.arr); // true
Copy after login

组合使用构造函数模式和原型模式

  • 是最常见的方式,构造函数模式用于定义实例属性,原型模式用于定义方法和共享的属性。

  • 优点:

    每个实例都有自己的一份实例属性的副本, 同时又共享着对方法的引用,最大限度节省内存。

    支持向构造函数传递参数

    <>


"use strict";
// *****************************************************************
// 组合使用构造函数模式和原型模式
function Person(id, name) {    
    this.id = id;    
    this.name = name;    
    this.friends = [1, 2, &#39;3&#39;];
}
Person.prototype = {
    constructor: Person,
    sayName: function() {
        console.log(this.name);
    }
}
var person1 = new Person(1,"p1_name");
var person2 = new Person(2,"p2_name");
person1.friends.push("4");
console.log(person1.friends); // 1,2,3,4 不会相互影响
console.log(person2.friends); // 1,2,3
console.log(person1.friends === person2.friends); // false
console.log(person1.sayName === person2.sayName); // true 共用一个代码块
Copy after login

动态原型模式

  • 将所有信息都封装在构造函数中,通过在构造函数中初始化原型(必要情况下)由保持了同时使用构造函数和原型的优点

  • 优点:

    可以通过检查某个应该存在的方法是否有效,来决定是否需要初始化原型

  • p.s.

    在该模式下不能使用对象字面量重写原型。如果在已经创建了实例的情况下重写原型,会切断现有实例和新原型之间的联系。

    <>


"use strict";
// *****************************************************************
// 组合使用构造函数模式和原型模式
function Person(id, name) {    
    this.id = id;    
    this.name = name;    
    this.friends = [1, 2, &#39;3&#39;];    
    // 只有在sayName()方法不存在的情况下,才会将它添加到原型中
    // if这段代码只会在初次调用构造函数时才会执行
    // 这里对原型所做的修改,能够立即在所有实例中得到反映
    if (typeof this.sayName != "function") {
        Person.prototype.sayName = function() {
            console.log(this.name);
        }
    }
}
var person1 = new Person(1,"hugh");
person1.sayName();
Copy after login

寄生构造函数模式

  • 在前几种模式不适用的情况下,可以使用寄生(parasitic)构造函数模式

  • 创建一个函数,仅封装创建对象的代码,然后返回新创建的对象

  • 和工厂模式的区别:使用new操作,并把使用的包装函数叫做构造函数

  • 使用场景:假设我们想创建一个具有额外方法的特殊数组,由于不能直接修改Array构造函数,就可以使用这个模式(见代码)

  • p.s.

    返回的对象与构造函数或与构造函数的原型属性之间没有关系,也就是说,构造函数返回的对象与在构造函数外部创建的对象没有不同

    不能依赖instanceof操作符来确定对象类型

    如果可以使用其他模式的情况下,不要使用这种模式

    <>


"use strict";
// *****************************************************************
function Person(id, name) {    
    var o = new Object();
    o.id = id;
    o.name = name;
    o.sayName = function() {
        console.log(this.name);
    }    
    return o; // 返回新创建的对象
}
var person1 = new Person(1, "111");
person1.sayName();

// 模拟使用场景
function SpecialArray() {    
    var values = new Array(); // 创建数组
    values.push.apply(values, arguments); // 添加值
    values.toPipedString = function() {        
        return this.join("|");
    };    
    return values;
}
var colors = new SpecialArray("red","blue","green");
console.log(colors);
console.log(colors.toPipedString());
Copy after login

稳妥构造函数模式

  • 所谓稳妥对象,指的是没有公共属性而且其方法也不引用this的对象

  • 使用场景:

    安全的环境中(这些环境会禁止使用thisnew

    防止数据被其他应用程序(如Mashup程序)改动时使用

  • 与寄生构造函数模式的区别:

    新建对象时不引用this

    不适用new操作符构造函数

  • 与寄生构造函数模式类似,该模式创建的对象与构造函数之间也没有什么关系,instanceof操作符也无意义

    <>


"use strict";
// *****************************************************************
function Person(id, name) {    
    var o = new Object();
    o.id = id;
    o.name = name;    
    // p.s.在该模式下,除了sayName()方法外,没有其他办法访问name的值
    o.sayName = function() {
        console.log(name);
    }    
    return o;
}
var person1 = Person(1, "111");
person1.sayName();
// console.log(personn1.name); // Error:person1 is not defined
Copy after login

The above is the detailed content of 9 ways to create objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!