- JavaScript is a dynamic language that allows you to add properties to objects at run time, or to Delete (delete) Properties
Property Name: The method name is also possible. Because the function itself is an object.
<! DOCTYPE html>
- Several ways to define objects in JavaScript (there is no concept of classes in JavaScript, only objects)
- The first way: Extend its properties and methods based on existing objects
<script type= "Text/javascript" >//01. Expands its properties and methods based on existing objects Var object=new object (); Object.username= "Zhangsan"; o Bject.sayname=function (name) { this.username=name; alert (this.username);} alert (object.username); Object.sayname ("Lisi"); alert (object.username);</script>
This approach has limitations because JavaScript does not have the concept of a class like Java, writes a class, and then new can get an object with these properties and methods.
At this point, if you want to have object2 can only write a copy of the above code, which is not very good.
- The second way: Factory mode
Similar to the static factory method in Java.
Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code
There are drawbacks to creating objects in this way (each object has a get method that wastes memory) and an improved factory approach (all objects share a Get method):
<! DOCTYPE html>
- The Third Way: constructor method defining an object
<! DOCTYPE html>
- Fourth Way: prototype (Prototype) way to create an object
Prototype is a property in an object, and all person objects can also have prototype properties.
You can add some properties to the object's prototype, methods.
The disadvantage of creating an object with a simple prototype: ① cannot pass arguments, it can only change its value after the object is created
② may cause program errors
<! DOCTYPE html>
<! DOCTYPE html>
Simply using a prototype to define an object cannot be used to assign an initial value to a property in a constructor, but only after the object has been generated, the property value is changed.
- The fifth way: Use the prototype + constructor to define the object---- recommended
- Properties between objects do not interfere with each other
- Share the same method across objects
<! DOCTYPE html>
- The Sixth way: Dynamic prototyping mode---- Recommended Use
in the constructor, the flags allow all objects to share a method, and each object has its own properties.
<! DOCTYPE html>
Tags: JavaScript, objects, constructsJavaScript constructor method definition object (reprint)