如:javascript
var jsstring = "var un = 1;"; eval(jsstring); console.log(typeof un); // "number"
方法1:使用new Function()。new Function()中的代码将在局部函数空间中运行。css
var jsstring = "var un2 = 1;"; new Function(jsstring)(); console.log(typeof un2); // "undefined"
方法2:将eval()封装到一个即时函数中。html
var jsstring = "var un3 = 1;"; (function() { eval(jsstring); })() console.log(typeof un3); // "undefined"
(function() { var local = 1; eval("local = 3; console.log(local); "); // 3 console.log(local); // 3 })(); (function() { var local = 1; new Function("console.log(typeof local);")(); // undefined })();
做用:java
function Waffle() { if (!(this instanceof Waffle)) { // 或者: if (!(this instanceof arguments.callee)) { return new Waffle(); } this.tastes = "yummy"; } Waffle.prototype.wantAnother = true; // 测试调用 var first = new Waffle(), second = Waffle(); console.log(first.tastes); // yummy console.log(second.tastes); // yummy console.log(first.wantAnother); // true console.log(second.wantAnother); // true
var a = new Array(3); console.log(a.length); // 3 console.log(a[0]); // undefined var a = new Array(3.14); // RangeError: invalid array length console.log(typeof a); // undefined;
使用Array()构造函数,返回一个具备255个空白字符的字符串:数组
var white = new Array(256).join(' ');
ES5定义了Array.isArray()方法。或调用Object.prototype.toString()方法。浏览器
if (typeof Array.isArray() === 'undefined') { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } }
函数体内部,以一个新函数覆盖了旧函数,回收了旧函数指针以指向一个新函数。即,该函数以一个新的实现覆盖并从新定义了自身。缓存
var scareMe = function() { alert("Boo!"); scareMe = function() { alert("Double boo!"); } } // 使用自定义函数 scareMe(); // Boo! scareMe(); // Double boo!
做用1:存储私有数据。即时函数能够返回函数,所以能够利用即时函数的做用域存储一些私有数据,而这特定于返回函数的内部函数。安全
var getResult = (function() { var res = 2+2; return function() { return res; } })(); console.log(getResult()); // 4
做用2:定义对象属性。数据结构
var o = { message: (function() { var who = "me", what = "call"; return what + " " + who; })(), getMsg: function() { return this.message; } } // 用法 console.log(o.getMsg()); // call me console.log(o.message); // call me
使用带有init()方法的对象,该方法在建立对象后将会当即执行。init()函数负责全部的初始化任务。闭包
优势:能够在执行一次初始化任务时保护全局命名空间。
这种模式主要适用于一次性任务,并且init()完毕后也没有对该对象的访问。若是想在init()完毕后保存对该对象的一个引用,能够在init()尾部添加return this
({ max: 60, getMax: function() { return this.max; }, // 初始化 init: function() { console.log(this.getMax()); // 60 // 更多初始化任务 } }).init();
函数能够在任什么时候候将自定义属性添加在函数中。自定义属性的其中一个用例是缓存函数结果(即返回值),所以,在下一次调用该函数时就不用重作潜在的繁重计算。
能够为函数建立一个属性cache,该属性是一个对象,其中使用传递给函数的参数做为键,而计算结果做为值。计算结果能够是须要的任意复杂数据结构。对于有更多以及更复杂的参数,通用的解决方案是将它们序列化。例如,能够将参数对象序列化为一个JSON字符串,并使用该字符串做为cache对象的键。
var myFunc = function() { var cachekey = JSON.stringify(Array.prototype.slice.call(arguments)), result; if (!myFunc.cache[cachekey]) { result = {}; // ``` 开销很大的操做``` console.log('Do Job'); myFunc.cache[cachekey] = result; } return myFunc.cache[cachekey]; } // 缓存存储 myFunc.cache = {}; // 测试 myFunc(0); // Do Job myFunc(0); // 无
function curry(fn) { var slice = Array.prototype.slice, stored_args = slice.call(arguments, 1); return function() { var new_args = slice.call(arguments), args = stored_args.concat(new_args); return fn.apply(null, args); } } // 普通函数 function add(a, b, c, d, e) { return a + b + c + d + e; } // 可运行于任意数量的参数 curry(add, 1, 2, 3)(5, 5); // 16 // 两步curry化 var addOne = curry(add, 1); addOne(10, 10, 10, 10); // 41 var addSix = curry(addOne, 2, 3); addSix(5, 5); // 16
添加到命名空间的一些属性可能已经存在,这致使可能会覆盖它们。所以,在添加一个属性或者建立一个命名空间以前,最好是首先检查它是否已经存在:
if (typeof MYAPP === 'undefined') { var MYAPP = {}; } // 或者: var MYAPP = MYAPP || {};
能够定义一个处理命名空间细节的可重用的函数。这个实现是非破坏性的,也就是说,若是已经存在一个命名空间,便不会再从新建立它。
var MYAPP = MYAPP || {}; MYAPP.namespace = function(ns_string) { var parts = ns_string.split('.'), parent = MYAPP, i; // 剥离最前面的冗余全局变量 if (parts[0] === "MYAPP") { parts = parts.slice(1); } for (i=0; i<parts.length; i++) { // 若是不存在,就建立一个属性 parent[parts[i]] = parent[parts[i]] || {}; parent = parent[parts[i]]; } return parent; } // 测试 var module1 = MYAPP.namespace('MYAPP.modules.module1'); module1 === MYAPP.modules.module1; // 忽略最前面的MYAPP var module2 = MYAPP.namespace('modules.module2'); module2 === MYAPP.modules.module2; // 长命名空间 MYAPP.namespace('one.two.three.four.five.six.seven.eight'); P93. 声明依赖 var myFunction() { // 依赖 var event = YAHOO.util.Event, dom = YAHOO.util.Dom; // 使用事件和DOM变量 // ... }
构造函数建立一个闭包,而在闭包范围内部的任意变量都不会暴露给构造函数之外的代码。然而,这些私有变量仍然能够用于公共方法中,也称为特权方法。
function Gadget(){ // 私有成员 var name = 'iPod'; // 公有函数或特权方法 this.getName = function() { return name; } } // 测试 var toy = new Gadget(); console.log(toy.name) // undefined console.log(toy.getName()); // iPod
私有性失效:当直接从一个特权方法中返回一个私有变量,且该变量刚好是一个对象或者数组,那么外面的代码仍然能够访问该私有变量。由于这是经过引用传递的。
function Gadget() { // 私有成员 var specs = { screen_width: 320, screen_height: 480, color: "white" }; // 公有函数或特权方法 this.getSpecs = function() { return specs; } } // 测试 var toy = new Gadget(), specs = toy.getSpecs(); specs.color = "black"; specs.price = "free"; console.dir(toy.getSpecs());
私有性失效的解决方法:
使getSpecs()返回一个新对象,该对象仅包含客户关注的原对象中的数据。即最低受权原则。
使用一个通用性的对象克隆函数,以建立specs对象的副本。如浅复制、深复制。
可使用一个额外的匿名即时函数建立闭包来实现私有性。
方法1:
var myobj; (function(){ // 私有成员 var name = "Peter"; // 公有部分 myobj = { // 特权方法 getName: function() { return name; } } })(); // 测试 console.log(myobj.name) // undefined console.log(myobj.getName()); // iPod
方法2:模块模式
var myobj = (function(){ // 私有成员 var name = "Peter"; // 公有部分 return { getName: function() { return name; } } })(); // 测试 console.log(myobj.name) // undefined console.log(myobj.getName()); // iPod
当私有成员与构造函数一块儿使用时,一个缺点在于每次调用构造函数以建立对象时,这些私有成员都会被从新建立。为了不复制工做以节省内存,能够将经常使用属性和方法添加到构造函数的prototype属性中。这样,经过同一个构造函数建立的多个实例,能够共享常见的部分数据。
可使用如下两个模式的组合:构造函数中的私有属性,以及对象字面量中的私有属性。因为prototype属性仅是一个对象,所以可使用对象字面量建立该对象。
function Gadget() { // 私有成员 var name = 'iPod'; // 公有函数或特权方法 this.getName = function() { return name; } } Gadget.prototype = (function() { // 私有成员 var browser = "Mobile Webkit"; // 公有原型成员 return { getBrowser: function() { return browser; } } })(); // 测试 var toy = new Gadget(); console.log(toy.getName()); // iPod console.log(toy.getBrowser()); // Mobile Webkit
模块模式是如下模式的组合:
方法1:返回对象
MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function() { // 依赖 var uobj = MYAPP.utilities.object, ulang = MYAPP.utilities.lang, // 私有属性 array_string = "[object Array]", ops = Object.prototype.toString; // 私有方法 // ... // 可选的一次性初始化过程 console.log('Creating namespace: array'); // 公有API return { isArray: function(a) { return ops.call(a) === array_string; } // ...更多方法和属性 } })();
方法2:返回构造函数
MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function(){ // 依赖 var uobj = MYAPP.utilities.object, ulang = MYAPP.utilities.lang, // 私有属性和方法 Constr; // 可选的一次性初始化过程 console.log('Creating namespace: array'); // 公有API——构造函数 Constr = function(o) { this.elements = this.toArray(o); }; // 公有API——原型 Constr.prototype = { constructor: MYAPP.utiltities.array, version: "2.0", toArray: function(obj) { for (var i=0, a=[], len=obj.length; i<len; i++) { a[i] = obj[i]; } return a; } } // 返回新的构造函数 return Constr; })(); // 测试 var arr = new MYAPP.utilities.array(obj);
静态属性和方法,是指从一个实例到另外一个实例都不会发生改变的属性和方法。
静态成员的优势:能够包含非实例相关的方法和属性,而且不会为每一个实例从新建立静态属性。
可使用构造函数,而且向其添加属性这种方式。静态成员,不须要特定的对象就可以运行。同时为了使实例对象也能够调用静态成员,只须要向原型中添加一个新的成员便可,其中该新成员做为一个指向原始静态成员的外观。
// 构造函数 var Gadget = function() {}; // 静态方法 Gadget.isShiny = function() { return 'you bet'; }; // 向原型中添加一个普通方法 Gadget.prototype.setPrice = function(price) { this.price = price; } // 向原型中添加一个外观 Gadget.prototype.isShiny = Gadget.isShiny; // 测试 // 调用静态方法 Gadget.isShiny(); // you bet; // 实例调用普通方法 var iphone = new Gadget(); iphone.setPrice(500); // 实例调用静态方法 iphone.isShiny(); // you bet
私有静态成员具备以下属性:
实现方法:闭包+即时函数。可参考模块模式的返回构造函数。
// 构造函数 var Gadget = (function() { // 静态变量 var counter = 0, NewGadget; // 新的构造函数的实现 NewGadget = function() { counter ++; }; // 特权方法 NewGadget.prototype.getLastId = function() { return counter; }; // 覆盖该构造函数 return NewGadget; })(); // 测试 var iphone = new Gadget(); console.log(iphone.getLastId()); var ipod = new Gadget(); console.log(ipod.getLastId()); var ipad = new Gadget(); console.log(ipad.getLastId());
做用:向构造函数的原型中添加新方法。
if (typeof Function.prototype.method !== "function") { Function.prototype.method = function(name, implementation) { this.prototype[name] = implementation; return this; // 返回this(指向构造函数),支持链式调用 } } // 测试 // 构造函数 var Person = function(name) { this.name = name; }. method('getName', function() { return this.name; }). method('setName', function(name) { this.name = name; return this; }); // 对象 var a = new Person('Adam'); a.getName(); // Adam; a.setName('Eve').getName(); // Eve
实现方式:
// 父构造函数 function Parent(name) { this.name = name || 'Adam'; } // 向原型中添加方法 Parent.prototype.say = function() { return this.name; } // 子构造函数(空白) function Child(name) {} // 继承:设置原型 Child.prototype = new Parent(); // 测试 var kid = new Child(); kid.say(); // Adam
原型链:
注意:
__proto__
属性仅用来解释原型链,不可用于开发中。// 演示缺点1 var s = new Child('Seth'); s.say(); // Adam
// 演示缺点2 // 父构造函数 function Article() { this.tags = ['js', 'css']; } var article = new Article(); // 子构造函数及继承 function Blog() {} Blog.prototype = article; // 子对象意外修改父对象的引用属性 var blog = new Blog(); blog.tags.push('html'); console.log(article.tags.join(' ')); // js css html
实现方式:
// 父构造函数 function Parent(name) { this.name = name || 'Adam'; } // 向原型中添加方法 Parent.prototype.say = function() { return this.name; } // 子构造函数 function Child(name) { // 继承:借用构造函数 Parent.apply(this, arguments); } // 测试 var kid = new Child('Partrick'); kid.name; // Partick typeof kid.say; // undefined
原型链:
注意:
实现方式:
// 父构造函数 function Parent(name) { this.name = name || 'Adam'; } // 向原型中添加方法 Parent.prototype.say = function() { return this.name; } // 子构造函数 function Child(name) { // 继承:借用构造函数 Parent.apply(this, arguments); } // 继承:设置原型 Child.prototype = new Parent(); // 测试 var kid = new Child('Partrick'); kid.name; // Partick kid.say(); // Partick delete kid.name; kid.say(); // Adam
原型链:
注意:
实现方式:
// 父构造函数 function Parent(name) { this.name = name || 'Adam'; } // 向原型中添加方法 Parent.prototype.say = function() { return this.name; } // 子构造函数 function Child() {} // 继承:共享原型 child.prototype = Parent.prototype;
原型链:
注意:
实现方式:
// 父构造函数 function Parent(name) { this.name = name || 'Adam'; } // 向原型中添加方法 Parent.prototype.say = function() { return this.name; } // 子构造函数 function Child(name) {} // 继承:设置原型 inherit(Child, Parent); // 实现: function inherit(C, P) { var F = function() {}; F.prototype = P.prototype; C.prototype = new F(); C.prototype.constructor = C; } // 优化:避免在每次须要继承时,都建立临时(代理)构造函数。 // 实现:即时函数+闭包 var inherit2 = (function() { var F = function() {}; return function(C, P) { F.prototype = P.prototype; C.prototype = new F(); C.prototype.constructor = C; } })(); // 测试 var kid = new Child(); kid.say(); // undefined kid.name = "Peter"; kid.say(); // Peter
原型链:
注意:
实现方式:
function object(P) { var F = function() {}; F.prototype = P; return new F(); }
对象字面量方式建立父对象
var parent = { name: "papa" } var child = object(parent); // 测试 console.log(child.name);
构造函数方式建立父对象
// 父构造函数 function Parent() { this.name = "papa"; } Parent.prototype.getName = function() { return this.name; } // 建立一个父对象 var papa = new Parent(); // 继承方式1:父构造函数中的this属性、父原型的属性都被继承 var kid = object(papa); console.log(typeof kid.name); // string console.log(typeof kid.getName); // function // 继承方式2:仅继承父原型的属性 var kid = object(Parent.prototype); console.log(typeof kid.name); // undefined console.log(typeof kid.getName); // function
ES5: Object.create()
在使用浅复制时,若是改变了子对象的属性,而且该属性刚好是一个对象,那么这种操做也将修改父对象。
function extend(parent, child) { var i; child = child || {}; for (i in parent) { if (parent.hasOwnProperty(i)) { child[i] = parent[i]; } } return child; } // 测试 var dad = { counts: [1, 2, 3], reads: { paper: true } }; var kid = extend(dad); kid.counts.push(4); dad.counts.toString(); // 1,2,3,4 dad.reads === kid.reads; // true
检查父对象的某个属性是否为对象,若是是,则须要递归复制出该对象的属性。
function extendDeep(parent, child) { var i, toStr = Object.prototype.toString, astr = "[object Array]"; child = child || {}; for (i in parent) { if (parent.hasOwnProperty(i)) { if (typeof parent[i] === 'object') { child[i] = (toStr.call(parent[i]) === astr) ? [] : {}; extendDeep(parent[i], child[i]); } else { child[i] = parent[i]; } } } return child; } // 测试 var dad = { counts: [1, 2, 3], reads: { paper: true } }; var kid = extendDeep(dad); kid.counts.push(4); dad.counts.toString(); // 1,2,3 dad.reads === kid.reads; // false
从多个对象中复制出任意成员,并将这些成员组合成一个新的对象。
遇到同名属性,老是使用靠后对象的值,即越日后优先级越高。
function mix() { var i, prop, child = {}; for (i = 0; i<arguments.length; i++) { for (prop in arguments[i]) { if (arguments[i].hasOwnProperty(prop)) { child[prop] = arguments[i][prop]; } } } return child; } // 测试 var cake = mix( { eggs: 2, large: true }, { buter: 1, saleted: true }, { flour: "3 cups" }, { sugar: "sure!" }, { eggs: 3 } // 同名属性,越日后优先级越高 ); console.dir(cake);
function bind(obj, fn) { return function() { return fn.apply(obj, Array.prototype.slice.call(arguments)); }; }
ES5: Funtion.prototype.bind()
if (typeof Function.prototype.bind === 'undefined') { Function.prototype.bind = function(obj) { var fn = this, slice = Array.prototype.slice, args = slice.call(arguments, 1); return function() { return fn.apply(obj, args.concat(slice.call(arguments))); } ; }; }
function lazyload(file) { var script = document.createElement("script"); script.src = file; document.getElementsByTagName("head")[0].appenChild(script); } // 使用 window.onload = function() { lazyload('extra.js'); }
function require(file, callback){ var script = document.createElement ("script"); script.type = "text/javascript"; if (script.readyState){ //IE script.onreadystatechange = function(){ if (script.readyState === "loaded" || script.readyState === "complete"){ script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function(){ callback(); }; } script.src = file; document.getElementsByTagName("head")[0].appendChild(script); } // 使用 require("extra.js", function() { // 执行extra.js中定义的函数 });
<object>
来代替脚本元素,并向其data属性指向脚本的URL。var preload; if (/*@cc_on!@*/false) { // 使用条件注释的IE嗅探 preload = function(file) { new Image().src = file; }; } else { preload = function(file) { var obj = document.createElement('object'); obj.width = 0; obj.height = 0; obj.data = file; document.body.appendChild(obj); }; } // 使用: preload('extra.js');