A brief discussion on 8 modes of creating objects in JS
1.Object mode
var o1 = {};//字面量的表现形式 var o2 = new Object; var o3 = new Object(); var o4 = new Object(null); var o5 = new Object(undefined); var o6 = Object.create(Object.prototype);//等价于 var o = {};//即以 Object.prototype 对象为一个原型模板,新建一个以这个原型模板为原型的对象 //区别 var o7 = Object.create(null);//创建一个原型为 null 的对象
View the differences between each newly created object in chrome:
It can be seen that the objects created by the first 6 modes are all the same. The seventh difference is that although it is also an Object object, it does not have any attributes (including no attributes that can be inherited, because its prototype was not specified when it was created) )
2.Factory pattern
//工厂方法1 通过一个方法来创建对象 利用 arguments 对象获取参数设置属性(参数不直观,容易出现问题) function createCar(){ var oTemp = new Object(); oTemp.name = arguments[0];//直接给对象添加属性,每个对象都有直接的属性 oTemp.age = arguments[1]; oTemp.showName = function () { alert(this.name); };//每个对象都有一个 showName 方法版本 return oTemp; } createCar("tom").showName();//在 JS 中没有传递的实参,实际形参值为 undefined(这里的 age 为 undefined) createCar("tim",80).showName(); alert(createCar("tom") instanceof Object);//true 判断对象是否 Object 类或子类
//工厂方法2 通过传参设置属性(参数直观明了) function createCar(name,age){ var oTemp = new Object(); oTemp.name = name;//直接给对象添加属性,每个对象都有直接的属性 oTemp.age = age; oTemp.showName = function () { alert(this.name); };//每个对象都有一个 showName 方法版本 return oTemp; } createCar("tom").showName(); createCar("tim",80).showName(); alert(createCar("tom") instanceof Object);//true 判断对象是否 Object 类或子类
3.Constructor pattern
//构造器方法1 function Car(sColor,iDoors){ //声明为构造器时需要将函数名首字母大写 this.color = sColor; //构造器内直接声明属性 this.doors = iDoors; this.showColor = function(){ return this.color; };//每个 Car 对象都有自己的 showColor方法版本 this.showDoor = function () { return this.doors; } }
The problem with using method 1 is obvious, There is no way to reuse the showDoor method. Every time a new object is created, a new space will be opened in the heap. The improvements are as follows
//构造器方法2 function showDoor(){ //定义一个全局的 Function 对象 return this.doors; } function Car(sColor,iDoors){//构造器 this.color = sColor; //构造器内直接声明属性 this.doors = iDoors; this.showColor = function(){ return this.color; }; this.showDoor = showDoor();//每个 Car 对象共享同一个 showDoor 方法版本(方法有自己的作用域,不用担心变量被共享) } alert(new Car("red",2).showColor());//通过构造器创建一个对象并调用其对象方法
The problem above is that the semantics are not clear enough and the encapsulation of the class cannot be reflected. Improvements For prototype mode
4. Create objects through Function objects
We know that each time a function is declared, a Function instance JS function is actually created.
function function_name(param1,param2){alert(param1);} //等价于 var function_name = new Function("param1","pram2","alert(param1);");
var Car2 = new Function("sColor","iDoors", "this.color = sColor;"+ "this.doors = iDoors;"+ "this.showColor = function(){ return this.color; }" ); alert(new Car2("blue",3).showColor());
5.prototype mode
The attributes and methods added by the class through the prototype attribute are bound to the prototype domain of this class (actually a Prototype object), bound to this The attributes and methods in the domain have only one version and will only be created once.
The instance object of the class can directly call the properties and methods of the prototype domain of the class just like calling its own properties. The class can indirectly call the prototype property by calling it. Call the properties and methods in the prototype domain.
Note: After the object is instantiated through the class, there is no prototype property in the object, but the object can directly access the contents of the prototype domain of the class like accessing properties. The instance object has a private propertyproto,protoThe attributes contain the attributes and methods in the prototype domain of the class
方法1 function Car3(){}//用空构造函数设置类名 Car3.prototype.color = "blue";//每个对象都共享相同属性 Car3.prototype.doors = 3; Car3.prototype.drivers = new Array("Mike","John"); Car3.prototype.showColor = function(){ alert(this.color); };//每个对象共享一个方法版本,省内存。 var car3_1 = new Car3(); var car3_2 = new Car3(); alert(car3_1.color);//blue alert(car3_2.color);//blue alert(Car3.prototype.color);//blue car3_1.drivers.push("Bill"); alert(car3_1.drivers);//"Mike","John","Bill" alert(car3_2.drivers);//"Mike","John","Bill" alert(Car3.prototype.drivers);//"Mike","John","Bill" //直接修改实例对象的属性,解析器会先去找实例对象是否有这个属性(不会去找实例对象的 _proto_ 属性内的那些类的 prototype 属性,而是直接查看这个实例是否有对应的属性(与_proto_同级)) //如果没有则直接给这个实例对象添加该属性,但不会修改类的prototype域的同名属性,既实例对象的_proto_属性内的那些类 prototype 域属性不会被修改 car3_1.color = "red";//car3_1对象内无名为 color 的对象属性,故将该属性添加到该对象上 //解析器对实例对象读取属性值的时候会先查找该实例有无同名的直接属性 //如果没有,则查找__proto__属性内保存的那些 当前类的 prototype 域的属性 //有就返回,无则继续查找是否有原型链中的对应的方法属性 //有就返回,无则返回undefined alert(car3_1.color);//red alert(car3_2.color);//blue alert(car3_2.color2);//undefined //直接修改类的 prototype 域内的属性,不会影响该类的实例对象的对象属性,但会影响实例对象的_proto_属性(_proto_属性内存放的是类的 prototype 域的内容) Car3.prototype.color = "black"; alert(car3_1.color);//red 该对象有同名的直接属性,故不会去_proto_属性内查找类的 prototype 域的属性 alert(car3_2.color);//black 受影响 //直接修改实例对象的方法,解析器会先去找实例对象是否有这个方法(不会去找实例对象的 _proto_ 属性内的那些类的 prototype 域的方法,而是直接查看这个实例是否有对应的方法(与_proto_同级)) //如果没有则直接给这个实例对象添加该方法,但不会修改类的prototype域的同名方法,既实例对象的_proto_属性内的那些类 prototype 域方法不会被修改 //car3_1对象内无名为 showColor 的对象方法属性,故将该方法属性添加到该对象上 car3_1.showColor = function () { alert("new function"); } //解析器对实例对象调用方法属性的时候会先查找该实例有无同名的直接方法属性 //如果没有,则查找_proto_属性内保存的那些 当前类的 prototype 域的方法属性 //有就返回,无则继续查找是否有原型链中的对应的方法属性 //找到就返回,无则报错 car3_1.showColor();//new function car3_2.showColor();//blue car3_1.abcd();//直接报错 //直接修改类的 prototype 域内的方法属性,不会影响该类的实例对象的方法属性,但会影响实例对象的_proto_属性(_proto_属性内存放的是类的 prototype 域的内容) Car3.prototype.showColor = function () { alert("second function"); } car3_1.showColor();//new function 该对象有同名的方法属性,故不会去_proto_属性内查找类的 prototype 域的方法属性 car3_2.showColor();//second function 受影响
It can be seen that although using this method reduces the waste of memory, it still There is a problem. Once the properties of an object are changed, the proto internal property values of all objects instantiated by this class will also change accordingly (actually they are references). The improvements are as follows
6. Mixed mode of constructor mode and prototype mode
//每个对象有专属的属性不会与其他对象共享 function Car4(sColor,iDoors){ this._color = sColor;//私有属性变量名称头加下划线标识 this._doors = iDoors; this.drivers = new Array("Mike","John");//公有属性标识 } //所有对象共享一个方法版本,减少内存浪费 Car4.prototype.showColor = function () { alert(this._color); }; var car4_1 = new Car4("red",4); var car4_2 = new Car4("blue",3); car4_1.drivers.push("Bill"); alert(car4_1.drivers);//"Mike","John","Bill" alert(car4_2.drivers);//"Mike","John"
This is also one of the commonly used ways to create objects
7.Dynamic prototype mode
function Car5(sColor,iDoors,iMpg){ this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.drivers = new Array("Mike","John"); //使用标志(_initialized)来判断是否已给原型赋予了任何方法,保证方法永远只被创建并赋值一次 if(typeof Car5._initialized == "undefined"){//因为这里的标记是附加在类上,故如果后期直接对其进行修改,还是有可能出现再次创建的情况 Car5.prototype.showColor = function () {//为Car5添加一个存放在 prototype 域的方法 alert(this.color); }; Car5._initialized = true;//设置一个静态属性 } } var car5_1 = new Car5("red",3,25); var car5_2 = new Car5("red",3,25);
This mode enables the definition of classes in languages such as strongly typed languages such as java
8. Mixed factory mode
function Car6(){ var oTempCar = new Object; oTempCar.color = "blue"; oTempCar.doors = 4; oTempCar.showColor = function () { alert(this.color); }; return oTempCar; } var car6 = new Car6();
Because in Car6 () The new operator is called inside the constructor, so the second new operator (located outside the constructor) will be ignored.
The object created inside the constructor is passed back to the variable car6. In this way, in the object method Internal management has the same problems as the classic method (factory method). It should be avoided as much as possible .php.cn)!

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

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

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



Solution: 1. Check spelling and path; 2. Add reference to component; 3. Check registry; 4. Run as administrator; 5. Update or repair Office; 6. Check security software; 7. Use other versions Components; 8. View error messages; 9. Find other solutions. Detailed introduction: 1. Check spelling and path: Make sure there are no spelling errors in the name and path of the object, and the file does exist in the specified path; 2. Add references to components, etc.

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

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

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese
