1. Simple object creation using a singleton pattern of {} or JS
var Cat = {}; // json format Cat.name= "Kity"; // add a property and assign a value Cat.age=2 =function () {Console.log ( "Hello" +cat.name+ ", this year" +cat["Age"]+ "); // You can use "." To access the property, or you can use HashMap to access the //
Single-instance objects:
var person={ name:' Zhangsan ', eat:function() { Console.log ( "Chi") } };p erson.eat (); Call
2. Use function (functions) to simulate class (no parameter constructor)
2.1 Create an object that is equivalent to an instance of the new class
function Person () {} var personone=New person (); // define a function that, if there is a new keyword to "instantiate", then the function can be considered a class personone.name= "Dylan";p ersonone.hobby= " Coding ";p ersonone.work=function() {alert (Personone.name+" is coding now ... ");} Personone.work ();
2.2 can be implemented using a parametric constructor, which makes the definition more convenient and more extensible (recommended)
functionPet (name,age,hobby) { This. name=name;//This scope: current Object This. age=Age ; This. hobby=Hobby; This. eat=function() {alert ("My Name" + This. name+ ", I like" + This. hobby+ ", also a foodie"); }}varMaidou =NewPet ("Eat", 5, "sleep");//Instantiate/Create Objectmaidou.eat ();//calling the Eat method (function)
3. Use Factory mode to create (Object keyword)
var wcdog =new Object (); Wcdog.name= "Wang Choi"; wcdog.age=3; wcdog.work= function () { alert ("I Am" +wcdog.name+ ", Wang Woo ...");} wcdog.work ();
4. Prototype keywords by using prototype objects
function Dog () { } Dog.prototype.name= "Wang Choi"; Dog.prototype.eat=function() {alert (this. name+ "is a foodie"var Wangcai =new Dog (); Wangcai.eat ();
5. Mixed mode (prototypes and constructors)
function Car (name,price) { this. name=name; this. price= price;} Car.prototype.sell=function() { alert ("I am" +this. name+ ", I sell now" + This . price+ "million Yuan"); } var camry =new Car ("Camry", 27
6. Mode of dynamic prototyping (can be seen as a special case of mixed mode)
function Car (name,price) { this. name=name; this. price= price; if (typeof car.sell== "undefined") { Car.prototype.sell=function() { Alert ("I am" +this. name+ ", I sell now" +this. price+ "Million"); } Car.sell=true;} } var camry =new Car ("Camry"); Camry.sell ();
Several ways that JavaScript creates objects