Home Web Front-end JS Tutorial 9 ways to create objects in JavaScript

9 ways to create objects in JavaScript

Aug 04, 2017 am 11:59 AM
javascript js method

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

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to enter bios on Colorful motherboard? Teach you two methods How to enter bios on Colorful motherboard? Teach you two methods Mar 13, 2024 pm 06:01 PM

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Summary of methods to obtain administrator rights in Win11 Summary of methods to obtain administrator rights in Win11 Mar 09, 2024 am 08:45 AM

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Detailed explanation of Oracle version query method Detailed explanation of Oracle version query method Mar 07, 2024 pm 09:21 PM

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

See all articles