JavaScript 组件写法
1.Prototype
var Class = { create: function() { return function() { this.init.apply(this, arguments); } } } var A = Class.create(); A.prototype = { init: function(msg) { this.msg = msg; }, fn: function() { alert(this.msg); } }
var a = new A("myMsg"); a.fn();
2. 也有比较简单的方法
function A() {} //var A = function(){} A.prototype = { init: function(msg) { this.msg = msg; }, fn: function() { alert(this.msg); } }
var a = new A(); a.init("myMsg"); a.fn();
3.Jquery插件
(function($) { var methods = { init: function(options) {}, show: function() {} }; $.fn.demo = function(method) { // Method calling logic if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on ...demo...'); } }; })(jQuery);
4.Base
var a = Base.extend({ init: function(){} });
a.init();
var Animal = Base.extend({
constructor: function(name) {
this.name = name;
},
name: "",
eat: function() {
this.say("Yum!");
},
say: function(message) {
alert(this.name + ": " + message);
}
});