Make JS writing closer to OOP, and JS writing closer to OOP
The following code uses the JS prototype object to implement the class inheritance DEMO.
$ Is a jquery object
/// Public method // $. oop. newClass = function newClass (obj) {// function create () {// if (obj! = Null) // return obj (); //} // var c = new create (); // return c; //} // var person = $. oop. newClass (function () {// constructor function person () {} // public attribute person. prototype. age = 15; // public function person. prototype. eat = function () {alert ("I will eat") ;}; return person ;}); // programmer var programMonkey =$. oop. newClass (function () {// constructor function programMonkey () {} programMonkey. prototype = person. prototype; // inherit programMonkey. prototype. skill = "asp.net"; programMonkey. prototype. work = function () {alert ("I will work overtime") ;}return programMonkey ;}); var pm = new programMonkey (); // function pm of a person. eat (); // function pm of the program ape. work (); // output attribute alert ("others' talents" + pm. age + "years old, I am a" + pm. skill + "");
It is not simple to implement polymorphism because of some JS features.
// Shared function // $. oop. newClass = function (obj) {// function Create () {// if (obj! = Null) // return obj (); //} // var c = new Create (); // return c; //} var iPerson = $. oop. newClass (function () {// constructor function person () {} person. prototype. name; person. prototype. iq; person. prototype. eat; return person;}); // programmer var programMonkey = $. oop. newClass (function () {// constructor function programMonkey () {} programMonkey. prototype = iPerson. prototype; // inherit return programMonkey;}); // design the wet var designer =$. oop. newClass (function () {// constructor function designer () {} designer. prototype = iPerson. prototype; // inherit from return designer;}); var inputValue = "programmer"; var ip = new iPerson (); if (inputValue = "programmer ") {ip = new programMonkey (); ip. iq = 0; ip. eat = function (msg) {alert (msg + "eat bananas")} else if (inputValue = "design wet") {ip = new designer (); ip. iq = 100; ip. eat = function (msg) {alert (msg + "eat bananas")} ip. name = inputValue; ip. eat ("I am" + ip. name + "intelligence" + ip. iq + "");
The corresponding eat function is executed based on different input values.