Home > Web Front-end > JS Tutorial > javascript constructor method to define objects_Basic knowledge

javascript constructor method to define objects_Basic knowledge

WBOY
Release: 2016-05-16 16:22:38
Original
1554 people have browsed it

Javascript is a dynamic language that can add attributes to objects at runtime and delete attributes from objects

Copy code The code is as follows:




                                            



Attribute name: method name is also acceptable. Because the function itself is an object

javascript array sorting

Copy code The code is as follows:




                                            




Several ways to define objects in JavaScript (there is no concept of classes in JavaScript, only objects)

The first way: expand its properties and methods based on existing objects




This method has limitations, because javascript does not have the concept of a class like java. Write a class, and then new can get an object with these properties and methods.

If you want to own object2 at this time, you can only write another copy of the code above, which is not good.

Second method: Factory method

Similar to the static factory method in java.

Copy code The code is as follows:





                                            



The above method of creating objects has disadvantages (each object has a get method, thus wasting memory), the improved factory method (all objects share a get method):

Copy code The code is as follows:




                                            




Third way: constructor method to define objects




                                            





Fourth method: Create objects using prototype method
Prototype is an attribute in the object object, and all person objects can also have the prototype attribute.

You can add some attributes and methods to the prototype of the object.

Disadvantages of simply using the prototype method to create objects: ①Unable to pass parameters, you can only change its value after the object is created

② may cause program errors

Copy code The code is as follows:

复制代码 代码如下:





        



单纯使用原型方式定义对象无法再构造函数中为属性赋初值,只能在对象生成后再去改变属性值。

第五种方式: 使用原型 构造函数方式来定义对象----推荐使用

对象之间的属性互不干扰
各个对象之间共享同一个方法

复制代码 代码如下:





        



第六种方式: 动态原型方式----推荐使用

         在构造函数中通过标志量让所有对象共享一个方法,而每个对象拥有自己的属性。

复制代码 代码如下:





        



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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template