How to create an object:
1) Monomer
<! DOCTYPE html>var Tom = {name: ' Tom ' 18 function () {alert ( this .name); }, Showage: function () {A Lert ( this .age); } }; alert (tom.age); Tom.showname (); </script>
2) Factory mode: Create objects with a function (open, assemble, factory)
<! DOCTYPE html>functionPerson (name,age,job) {varo =NewObject (); O.name=name; O.age=Age ; O.job=job; O.showname=function() {alert ( This. Name); }; O.showage=function() {alert ( This. Age); }; returno; } varTom = person (' Tom ', ' engineer '); Tom.showname (); Tom.showage ()</script>3) Constructor (method repetition, disadvantage is memory consumption)
<! DOCTYPE html>functionPerson (name,age,job) { This. Name =name; This. Age =Age ; This. Job =job; This. ShowName =function() {alert ( This. Name); } } varTom =NewPerson (' Tom ', ' engineer '); Tom.showname ()</script>4) prototype mode (Create Class)
<! DOCTYPE html>functionPerson (name,age,job) { This. Name =name; This. Job =job; This. Age =Age ; } //in prototype binding method, this method can realize the common use of different instancesPerson.prototype.showname =function() {alert ( This. Name); }; varTom =NewPerson (' Tom ', ' engineer '); varJack =NewPerson (' Jack ', ' worker '); Tom.showname (); Jack.showname (); </script>Inherited:
<! DOCTYPE html>functionFclass (name,age) { This. Name =name; This. Age =Age ; } Fclass.prototype.showname=function() {alert ( This. Name); }; Fclass.prototype.showage=function() {alert ( This. Age); }; //attribute Inheritance: inherited by call or Apply method functionSclass (name,age,job) {//the This object that changes the execution of the current function: an object that points to a subclass instantiation //call:aa.call (' abc ', 2,3) //apply:aa.apply (' abc ', [2,3])Fclass.call ( This, Name,age); This. Job =job; } //method Inheritance: Assigns an instance of a parent class to the prototype property of a subclassSclass.prototype =NewFclass (); Sclass.prototype.showjob=function() {alert ( This. Job); }; varTom =NewSclass (' Tom ', ' engineer '); Tom.showage (); Tom.showname (); Tom.showjob (); </script>js--Object-oriented