Method One: 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, within which it uses the This keyword to refer to an instance object.
The properties and methods of the prototype class can also be defined on top of the constructor's object.
When generating an instance, use the New keyword.
Method Two: 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, "class" is an object, not a function.
Then, generate the instance directly with Object.create (), without the need for new.
Method Three: Minimalist method
Definition of Class 1
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 ();//Tomcat.sleep ();//ZZzz ...
It is convenient to have one class inherit another class. As long as in the former CreateNew () method, call the latter's CreateNew () method.
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, the methods and properties that are not defined on the Cat object are private.
Class 4 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 the instance objects to be able to read and write the same internal data.
This time, as long as the internal data, encapsulated in the class object inside the CreateNew () method outside can be.
JavaScript Object-oriented