Home >Web Front-end >JS Tutorial >10 ways to write classes in javascript_js object-oriented

10 ways to write classes in javascript_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:50:38861browse
10. How to write classes in mootools.js
The latest version of mootools.js is 1.2.3, and 1.2.0 is used here. mootool is designed to be a very compact, modular, object-oriented js library. Use Class class to write classes in mootool. The Class class is new from the Native class:
Copy code The code is as follows:

/*
*Script: Class.js
*/
var Class = new Native({
name: 'Class',

initialize: function(properties){
properties = properties || {};
var klass = function(empty){
for (var key in this) this[key] = $unlink(this[key]);
for (var mutator in Class .Mutators){
if (!this[mutator]) continue;
Class.Mutators[mutator](this, this[mutator]);
delete this[mutator];
}
this.constructor = klass;
if (empty === $empty) return this;

var self = (this.initialize) ? this.initialize.apply(this, arguments) : this;
if (this.options && this.options.initialize) this.options.initialize.call(this);
return self;
};

$extend(klass, this) ;
klass.constructor = Class;
klass.prototype = properties;
return klass;
}
});

Native method is one of mootools A very important method, many classes use it to assemble. Such as Window, Document, Event. Of course, there is also Class here. After importing mootools, we only need to use Class when writing classes. A Person class:
Copy code The code is as follows:

/**
* Person类
* @param {Object} name
*/
var Person = new Class({
initialize: function(name){
this.name = name;
},
setName : function(name) {
this.name = name;
},
getName : function() {
return this.name;
}
})

//new an object
var p = new Person("jack");

//Test set, get method
console.log(p.getName());//jac
p.setName('andy') ;
console.log(p.getName());//andy

//Test whether instanceof and p.constructor correctly point to Person
console.log(p instanceof Person); / /true
console.log(p.constructor == Person); //true

Native is actually just an ordinary function, which assembles a class (function) through the passed parameters. Finally return the class (function). Since Native is a function, the function calling method is (), call, apply. But in mootools, the new Native (obj) method is used. Why? The reason is just to make Native look more like a class.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn