Preface
Before learning object-oriented (object-oriented,oo) programming, you first need to know what an object is, ECMA-262, define an object as a collection of "unordered properties, whose properties can contain basic values, objects or functions". JavaScriptThere are many ways to create objects, such as: factory mode, constructor mode, prototype mode, combined constructor mode and prototype mode, parasitic constructor mode, etc.
1. Factory Pattern
The factory pattern is a well-known design pattern in the field of software engineering. This pattern abstracts the process of creating specific objects. Considering that classes cannot be created in ECMAScript , developers invented a function that encapsulates the details of creating objects with a specific interface.
function createStudent(name, age, job){ var o = new Object(); o.name = name; o.age = age; o.job = job; o.sayName = function(){ alert(this.name); }; return o; } var student1= createStudent("xiaoming", 9, "student"); var student2 = createStudent("xiaowagn", 15, "student");
The function createStudent() can construct a Student object containing all necessary information based on the accepted parameters. This function can be called an unlimited number of times, and each time it returns an object containing three properties and one method. Although the factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of object identification (that is, how to know the type of an object). With the development of JavaScript, another new pattern has emerged. 2. Constructor pattern
First we modify the previous code as follows:
function Student(name,age){ this.name=name; this.age=age; this.showname=function(){ alert(this.name); } } var xiaoming =new Student("xiaoming",6); var xiaogang =new Student("xiaogang",7);
Difference from factory pattern:
1.
No Display the created object2.
Assign the properties directly tothisobject 3.
There is noReturn statement. To create an instance, use the
newoperator. Steps to create an object:
1.
Create a new object2.
Assign the scope of the constructor Give the new object (this points to this new object)3.
Execute the code of the constructor and add attributes to this object4.
Return this object
alert(xiaoming.constructor==Student) //true;
The
attribute of the object is initially used to identify the type of an object . Check an object type, or use instanceofalert(xiaoming instanceof Student) //true
alert(xiaoming instanceof Object) //true是因为所有对象均继承自Object
Creating a custom constructor means that instances of it can be used in the future Identified as a specific type; this is where the constructor pattern outperforms the factory pattern. There are also disadvantages to using constructors.
That is, each method must be recreated on each instance.For example, , xiaoming and xiaogang have a showname() method. But those two methods are not instances of the same Function. ECMAScript Functions are objects, so every time a function is defined, an object is instantiated. From a logical perspective, the constructor can also be defined like this at this time. function student(name,age){
this.name=name;
this.showName=new Function(“alert(this.name)”);
}
It can be seen that each
instance contains a different Function instance. Functions with the same name on different instances are not equal. The following code demonstrates this. alert(xiaoming.showName==xiaogang.showname);//false
2. Constructor Pattern
Every function we create has a prototype (prototype) attribute. This attribute is a pointer pointing to an object, and the purpose of this object is to contain Properties and methods that can be shared by all instances of a specific type. If understood literally, prototype is the prototype object of the object instance created by calling the constructor. The advantage of using a prototype object is that all object instances can share the properties and methods it contains. In other words, instead of defining information about an object instance in the constructor, you can add this information directly to the prototype object.
function Student(){ } Student.property.name=”default name”; Student.property.age=0; Student.property.showName=funciton(){ alert(this.name); } Var xiaoming=new Student(); Var xiaogang=new Student();
与构造函数模式的不同时,新对象的这些属性和方法是由所有的实例共享的。换句话说xiaoming和xiaogang访问的都是同一组属性和同一个showName()函数。要理解原型模式的工作原理,必须先理解ECMAScript 中原型对象的性质。
1. 理解原型对象
无论什么时候,只要创建了一个新函数,就会根据一组特定的规则为该函数创建一个prototype
属性,这个属性指向函数的原型对象。在默认情况下,所有原型对象都会自动获得一个constructor
(构造函数)属性,这个属性包含一个指向prototype 属性所在函数的指针。就拿前面的例子来说,
Student.prototype. constructor 指向Student。而通过这个构造函数,我们还可继续为原型对象添加其他属性和方法.
在JS中我们通过isPropertyOf()来判断,某个实例是否指向某个函数的的原型。
Eg:
Student.property.isPropertyOf(xiaoming);//true。
在ECMAScript5中含增加了Object.getPropertyOf()方法来获取一个实例的原型
Eg:
alert(Object.getPropertyOf(xiaoming)==Student.property);//true alert(Object.getPropertyOf(xiaoming).name);//default name
此外,我们还可以通过hasOwnProperty()方法来检测一个属性是存在实例中还是存在原型中。alert(xiaoming.hasOwnProperty(“name”));//false
alert(xiaoming.property.hasOwnProperty(“name”));//true
原型模式也不是没有缺点。首先,它省略了为构造函数传递初始化参数这一环节,结果所有实例在默认情况下都将取得相同的属性值。虽然这会在某种程度上带来一些不方便,但还不是原型的最大问题。原型模式的最大问题是由其共享的本性所导致的。原型中所有属性是被很多实例共享的,这种共享对于函数非常合适。对于那些包含基本值的属性倒
也说得过去,毕竟(如前面的例子所示),通过在实例上添加一个同名属性,可以隐藏原型中的对应属性。然而,对于包含引用类型值的属性来说,问题就比较突出.
四、组合使用构造函数模式和原型模式
创建自定义类型的最常见方式,就是组合使用构造函数模式与原型模式。构造函数模式用于定义实例属性,而原型模式用于定义方法和共享的属性。结果,每个实例都会有自己的一份实例属性的副本,但同时又共享着对方法的引用,最大限度地节省了内存。另外,这种混成模式还支持向构造函数传递参数;可谓是集两种模式之长。
function Student(name,age){ this.name=name; this.age=age; } Student.property.showName=funciton(){alert(this.name);}
这种构造函数与原型混成的模式,是目前在ECMAScript 中使用最广泛、认同度最高的一种创建自定义类型的方法。可以说,这是用来定义引用类型的一种默认模式。
五、寄生构造函数模式
通常,在前述的几种模式都不适用的情况下,可以使用寄生(parasitic)构造函数模式。这种模式的基本思想是创建一个函数,该函数的作用仅仅是封装创建对象的代码,然后再返回新创建的对象;但从表面上看,这个函数又很像是典型的构造函数。
funciton Student(name,age){ Var o=new Object(); o.name=name; o.age=age; o.showName=function(){alert(this.name);} Reurn o; }
关于寄生构造函数模式,有一点需要说明:首先,返回的对象与构造函数或者与构造函数的原型属性之间没有关系;也就是说,构造函数返回的对象与在构造函数外部创建的对象没有什么不同。为此,不能依赖instanceof 操作符来确定对象类型。由于存在上述问题,我们建议在可以使用其他模式的情况下,不要使用这种模式。个人感觉这模式还是有点模仿工厂模式。
以上就是JavaScript面向对象编程(对象创建)的内容,更多相关内容请关注PHP中文网(www.php.cn)!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


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

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
