1, class inheritance, simulation of object-oriented language inheritance way
function extend (subclass, superclass) {
var F = function () {};
F.prototype = Superclass.prototype;
Subclass.prototype = new F ();
SubClass.prototype.constructor = subclass;
Subclass.superclass = Superclass.prototype;
if (SuperClass.prototype.constructor = = Object.prototype.constructor) {
SuperClass.prototype.constructor = superclass;
}
}
2, cloning, the realization of prototype inheritance, JavaScript is unique to the object as a blueprint for the inheritance way
function Clone (object) {
var F = function () {};
F.prototype = object;
return new F ();
}
3, JavaScript simulation of object-oriented Language interface (INTERFACE) Implementation mode
First, declare the Interface constructor
var Interface = function (name, methods) {
if (arguments.length! = 2) {
throw new Error ("Interface constructor called with" + arguments.length
+ "arguments, Bue expected exactly 2.");
}
THIS.name = name;
This.methods = [];
for (var i = 0, len = methods.length; i < Len; i++) {
if (typeof Methods[i]!== ' string ') {
throw new Error ("Interface constructor expects method names to be"
+ "passed in as a string.");
}
This.methods.push (Methods[i]);
}
}
Defines a class method for Interface that detects if the object implements a method that specifies the interface?
Interface.ensureimplements = function (object) {
if (Arguments.length < 2) {
throw new Error ("Function interface.ensureimplements called with"
+ arguments.length+ "arguments, Bue expected at least 2.");
}
for (var i = 1, len = arguments.length; i < Len; i++) {
var interface = Arguments[i];
if (Interface.constructor!== interface) {
throw new Error ("Function Interface.ensureimplements expects arguments"
+ "both and above to be instances of Interface.");
}
for (var j = 0, Methodslen = interface.methods.length; J < Methodslen; J + +) {
var method = Interface.methods[j];
if (!object[method] | | | typeof method!== ' function ') {
throw new Error ("Function Interface.ensureImplements:object"
+ "does not implement the" + Interface.name
+ "interface. Method "+ Method +" is not found. ");
}
}
}
};
The following is an example/////////////////////////////////////////////////////////////////////////////////////////////////////// ////
Declaring an interface, simply declaring it, without implementing
var Composite = new Interface (' Composite ', [' Add ', ' Remove ', ' getchild ']);
Declaring an interface, simply declaring it, without implementing
var FormItem = new Interface (' FormItem ', [' Save ']);
Declaring the implemented class
function MenuItem (ID, method, action) {
...
This.show = function (object) {
Interface.ensureimplements (This, [Composite, MenuItem]);
Ensure that the class object implements the Composite, MenuItem interface, in order to perform the following logic
...
}
...
}
JavaScript Design Patterns-tool functions