How to create an object in javascript?
How to create an object in JavaScript: 1. Use the new keyword to call the constructor to create the object; 2. Use the factory method to create the object; 3. Use the constructor method to create the object; 4. Use the prototype method to create the object; 5. Use the mixed constructor/prototype method to create objects; 6. Use the dynamic prototype method to create objects.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
We can use the grammatical features of JavaScript to create objects with the idea of classes.
Method 1: Original method--use the new keyword to call the constructor to create an object
The code is as follows:
<script> var obj = new Object(); obj.name = "Kitty";//为对象增加属性 obj.age = 21; obj.showName = function () {//为对象添加方法 console.log(this.name); }; obj.showAge = function(){ console.log(this.age); }; obj.showName(); obj.showAge(); </script>
This method generates an object through the new keyword, and then adds properties and methods according to the characteristics of JavaScript as a dynamic language, and constructs an object. The this represents the object on which the method is called.
The problem with this method is that if we need to create objects multiple times, we need to repeat the code multiple times, which is not conducive to code reuse.
Method 2: Factory method
The code is as follows:
<script> function createObj(){ var obj = new Object();//创建对象 obj.name = "Kitty"; obj.age = "21"; obj.showName = function () { console.log(this.name); }; obj.showAge = function () { console.log(this.age); }; return obj; } var obj1 = createObj(); var obj2 = createObj(); obj1.showName(); obj1.showAge(); obj2.showName(); obj2.showAge(); </script>
Although this method also realizes the creation of objects, similarly, if you need to create objects multiple times and the attribute contents are different, you also need to repeat the code multiple times. The code reuse rate needs to be reconsidered, and then the code can be modified to increase the code reuse rate, and the factory method can be changed to pass in parameter assignments.
The improved code is as follows:
<script> function createObj(name,age){ var obj = new Object(); obj.name = name; obj.age = age; obj.showName = function () { console.log(this.name); }; obj.showAge = function(){ console.log(this.age); }; return obj; } var obj1 = new createObj("Kitty","21"); var obj2 = new createObj("Luo","22"); obj1.showName();//Kitty obj1.showAge();//21 obj2.showName();//luo obj2.showAge();//22 </script>
Although this method can improve the reuse of code Efficiency, but compared with the concept of classes in object-oriented, there is a big flaw. Object-oriented emphasizes that the properties of objects are private, but the methods of objects are shared. When the above factory method creates objects, it must create its own private method for each object. At the same time, it is a waste of memory because logically identical methods are created for each object.
The improved code is as follows:
<script> function createObj(name,age){ var obj = new Object(); obj.name = name; obj.age = age; obj.showName = showName; obj.showAge = showAge; return obj; } function showName(){ console.log(this.name); } function showAge(){ console.log(this.age); } var obj1 = new createObj("Kitty","21"); var obj2 = new createObj("Luo","22"); obj1.showName();//Kitty obj1.showAge();//21 obj2.showName();//luo obj2.showAge();//22 </script>
The above is solved by defining several function objects. It solves the private problem of function objects held by different objects. Now all object methods hold references to the above two functions. But in this way, the object's functions and objects are independent of each other, which is inconsistent with the object-oriented idea that specific methods belong to specific classes.
Method 3: Constructor method
The code is as follows:
<script> function Person(name,age){ this.name = name; this.age = age; this.showName = function () { console.log(this.name); }; this.showAge = function () { console.log(this.age); }; } var obj1 = new Person("Kitty","21"); var obj2 = new Person("Luo","22"); obj1.showName();//Kitty obj1.showAge();//21 obj2.showName();//luo obj2.showAge();//22 </script>
The constructor method is the same as the factory method, and will create an exclusive function object for each object. Of course, these function objects can also be defined outside the constructor, so that the objects and methods are independent of each other.
The biggest problem with using the constructor is that all properties will be created once for each instance. This is acceptable for numeric properties, but it is unreasonable if each instance of the function method must be created.
To create a new instance of Person(), you must use the new operator. Calling the constructor in this way actually goes through the following four steps:
- 创建一个新对象;
- 将构造函数的作用域赋给新对象(因此this就指向了这个新对象);
- 执行构造函数中的代码(为这个新对象添加属性);
- 返回新对象。
方法四:原型方法
代码如下:
<script> function Person(){} //定义一个空构造函数,且不能传递参数 //将所有的属性的方法都赋予prototype Person.prototype.name = "Kitty"; Person.prototype.age = 21; Person.prototype.showName = function (){ console.log(this.name); }; Person.prototype.showAge = function (){ console.log(this.age); }; var obj1 = new Person("Kitty","21"); var obj2 = new Person("Luo","22"); obj1.showName();//Kitty obj1.showAge();//21 obj2.showName();//luo obj2.showAge();//22 </script>
当生成Person对象时,prototype的属性都赋给了新的对象。那么属性和方法是共享的。首先,该方法的问题是构造函数不能传递参数,每个新生成的对象都有默认值。其次,方法共享没有任何问题,但是,当属性是可改变状态的对象时,属性共享就有问题。
修改代码如下:
<script> function Person(){} //定义一个空构造函数,且不能传递参数 //将所有的属性的方法都赋予prototype Person.prototype.age = 21; Person.prototype.array = new Array("Kitty","luo"); Person.prototype.showAge = function (){ console.log(this.age); }; Person.prototype.showArray = function (){ console.log(this.array); }; var obj1 = new Person(); var obj2 = new Person(); obj1.array.push("Wendy");//向obj1的array属性添加一个元素 obj1.showArray();//Kitty,luo,Wendy obj2.showArray();//Kitty,luo,Wendy </script>
上面的代码通过obj1的属性array添加元素时,obj2的array属性的元素也跟着受到影响,原因就在于obj1和obj2对象的array属性引用的是同一个Array对象,那么改变这个Array对象,另一引用该Array对象的属性自然也会受到影响,混合的构造函数/原型方式使用构造函数定义对象的属性,使用原型方法定义对象的方法,这样就可以做到属性私有,而方法共享。
方法五:混合的构造函数/原型方式
代码如下:
<script> function Person(name,age){ this.name = name; this.age = age; this.array = new Array("Kitty","luo"); } Person.prototype.showName = function (){ console.log(this.name); }; Person.prototype.showArray = function (){ console.log(this.array); }; var obj1 = new Person("Kitty",21); var obj2 = new Person("luo",22); obj1.array.push("Wendy");//向obj1的array属性添加一个元素 obj1.showArray();//Kitty,luo,Wendy obj1.showName();//Kitty obj2.showArray();//Kitty,luo obj2.showName();//luo </script>
属性私有后,改变各自的属性不会影响别的对象。同时,方法也是由各个对象共享的。在语义上,这符合了面向对象编程的要求。
方法六:动态原型方法
代码如下:
<script> function Person(name,age){ this.name = name; this.age = age; this.array = new Array("Kitty","luo"); //如果Person对象中_initialized 为undefined,表明还没有为Person的原型添加方法 if(typeof Person._initialized == "undefined"){ Person.prototype.showName = function () { console.log(this.name); }; Person.prototype.showArray = function () { console.log(this.array); }; Person._initialized = true; } } var obj1 = new Person("Kitty",21); var obj2 = new Person("luo",22); obj1.array.push("Wendy");//向obj1的array属性添加一个元素 obj1.showArray();//Kitty,luo,Wendy obj1.showName();//Kitty obj2.showArray();//Kitty,luo obj2.showName();//luo </script>
这种方法和构造函数/原型方式大同小异。只是将方法的添加放到了构造函数之中,同时在构造函数Person上添加了一个属性用来保证if语句只能成功执行一次,在实际应用中,采用最广泛的构造函数/原型方法。动态原型方法也很流行,它在功能上和构造函数/原型方法是等价的。不要单独使用构造函数和原型方法。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of How to create an object in javascript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
