Use apply, call to delegate, Don't reinvent the wheel
Blogs20152015-04-04
Use apply, call to delegate, Don’t reinvent the wheel
I saw some codes which try to implement everything from bottom, e.g write basic functions such as extend, proxy, bind, splice, indexOf etc. Actually besides npm/bower modules, We can use apply(), call() to delegate existed general methods. Here I use the following quick and simple way to do the reuse:
function AAA() {};
AAA.prototype.extend = function() {
jQuery.extend.apply(this, arguments);
}
//Then we can use exact jQuery's extend methods for AAA constructor:
var aaa = new AAA();
aaa.extend({getName: function() { return this.name; }});
aaa.name = 'william';
aaa.getName(); //william
//Same for angular:
aaa.__proto__.copy = function() {
angular.copy.apply(this, arguments);
}Use namespace instead of global variable
This is my way to do so, put them in Immediately-Invoked Function Expression (IIFE):
var myNameSpace = window.myNameSpace || {};
(function($, _, exports) {
'use strict';
function A() {}
function B() {}
...
exports.A = A;
exports.B = B;
}.call(this, jQuery, lodash, myNameSpace));
// myNameSpace will have 2 methods: A and B and can be used everywhere.using the namespace is better than global variables, safe and manageable.
