Method 1: Constructor method
function Cat(){ this.name = ""; } Cat.prototype.showName = function(){ console.log(this.name); } var cat = new Cat(); cat.name = "Tom"; cat.showName();// Tom
It simulates a "class" with a constructor, and inside it refers to the instance object with the this keyword.
The properties and methods of the class can also be defined on the prototype object of the constructor.
When creating an instance, use the new keyword.
Method 2: Object.create() method
var Cat = { name:"", showName:function(){ console.log(this.name); } }; var cat = Object.create(Cat); cat.name = "Tom"; cat.showName();// Tom
In this way, a "class" is an object, not a function.
Then, use Object.create() directly to generate an instance without using new.
Method 3: Definition of the Minimalism Method
1 Category
var Cat = { createNew:function(){ var cat = {}; cat.name = ""; cat.showName = function(){ console.log(this.name); } return cat; } }; var cat = Cat.createNew(); cat.name = "Tom"; cat.showName();// Tom
2 Inheritance
var Animal = { createNew:function(){ var animal = {}; animal.name = ""; animal.sleep = function(){ console.log("ZZzz..."); } return animal; } }; var Cat = { createNew:function(){ var cat = Animal.createNew(); cat.name = "Cat"; cat.showName = function(){ console.log(this.name); } return cat; } }; var cat = Cat.createNew(); cat.name = "Tom"; cat.showName();// Tom cat.sleep();// ZZzz...
It is convenient to have one class inherit from another class. Just call the createNew() method of the latter in the createNew() method of the former.
3 private members
var Cat = { createNew:function(){ var cat = {}; var name = "Tom"; // private cat.showName = function(){ console.log(name); } return cat; } }; var cat = Cat.createNew(); cat.showName();// Tom
In the createNew() method, as long as the methods and properties are not defined on the cat object, they are all private.
4 types of properties
var Cat = { className:"Cat", createNew:function(){ var cat = {}; cat.name = "";// private cat.showName = function(){ console.log(cat.name); } cat.showClass = function(){ console.log(Cat.className); } return cat; } }; var cat1 = Cat.createNew (); cat1.name = "Tom"; cat1.showName (); cat1.showClass(); var cat2 = Cat.createNew (); cat2.name = "Jim"; cat2.showName (); cat2.showClass();
Sometimes, we need all instance objects to be able to read and write the same internal data.
At this time, as long as this internal data is encapsulated inside the class object, that is, outside the createNew() method.