Created
October 21, 2013 14:09
-
-
Save Gaubee/7084513 to your computer and use it in GitHub Desktop.
使用Object.prototype的原型链绑定方式来实现with。
如果使用全局对象global或者window会导致原对象无法访问。
但是使用这种方法会导致作用域等级下降,同名变量无法正确访问。
比如说window中有一个name变量,则下面测试例子中的name无法正确访问。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function(G) { | |
| "use strict" | |
| var G = Object.prototype; | |
| G.With = function(withObj, withFun) { | |
| var keys = [], | |
| backup_Obj_pro = {}, | |
| i, | |
| len, | |
| key; | |
| for (i in withObj) { | |
| if (withObj[i] !== G[i]) { | |
| keys[keys.length] = i; | |
| console.log(i, i in G, G[i]) | |
| if (i in G) { | |
| backup_Obj_pro[i] = G[i]; | |
| } | |
| G[i] = withObj[i]; | |
| } | |
| } | |
| withFun(); | |
| for (i = 0, len = keys.length; i < len; i += 1) { | |
| key = keys[i]; | |
| withObj[key] = G[key]; | |
| if (backup_Obj_pro.hasOwnProperty(key)) { | |
| G[key] = backup_Obj_pro[key]; | |
| } else { | |
| delete G[key] | |
| } | |
| } | |
| } | |
| })(); | |
| var obj = { | |
| name: "Gaubee", | |
| age: 21 | |
| } | |
| With(obj, function() { | |
| console.log(name, "is", age, "years old"); | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment