我已經構造一個相當有用的功能,以確定數據類型;然而,在編碼愉快的時候,我被一個相當令人擔憂的困境粗暴地打斷了。的JavaScript - 訪問屬性後(閉合).bind()
正如您所知,在關閉後調用.bind({foo:'bar'})
後,您無法訪問foo
屬性「外部」;然而,在關閉,this.foo
工程。
而且,以這樣的方式分配東西的時候,你經常會遇到一拋:intermediary ... blah blah is undefined
當您嘗試訪問屬性 - 定義後直接。下面的代碼解決這些問題,但...
問題是代碼後解釋說:
"use strict";
if ('undefined' == typeof global)
{
Object.defineProperty
(
window,'global',
{
writable:false,
configurable:false,
enumerable:false,
value:window
}
);
}
Object.defineProperty
(
Function.prototype, 'wrap',
{
writable:false,
enumerable:false,
configurable:false,
value:function(jsob)
{
this.bind(jsob);
for (var i in jsob)
{ this[i] = jsob[i]; }
return this;
}
}
);
global.typeOf = function(data)
{
if ((data === null) || (data === undefined))
{ return 'void'; }
if ((data === true) || (data === false))
{ return 'bool'; }
var tpof = (({}).toString.call(data).match(/\s([a-zA-Z]+)/)[1].toLowerCase());
if ((tpof == 'array') || (tpof == 'htmlcollection') || (tpof == 'namednodemap'))
{ return 'list'; }
if ((tpof == 'global') || (tpof == 'window'))
{ return 'glob'; }
switch (tpof.substr(0,6))
{
case 'number': return 'unit';
case 'string': return (/[^\x20-\x7E\t\r\n]/.test(data) ? 'blob' : 'text');
case 'object': return 'jsob';
case 'functi': return 'func';
default: return 'node';
}
}
.wrap
({
list:'void bool unit text blob list jsob func node glob'.split(' '),
init:function()
{
this.list.forEach(function(item)
{
global[(item.toUpperCase())] = item;
global[('is'+(item[0].toUpperCase() + item.substr(1,item.length)))] = function(data)
{
return ((typeOf(data) == this.text) ? true : false);
}
.bind({text:item.toLowerCase()}); // <-- ISSUE
});
return this;
}
}).init();
所以上面的小wrapper
照顧這種古怪的;然而,看看<-- ISSUE
是哪一行;看,我不能使用wrap()
那裏,我不得不使用bind()
,否則 - 裏面的功能 - this
是未定義的!
讓我澄清一下:如果你使用的整個代碼只是因爲它是上面一個品牌打屁股新的HTML文件中<script>
標籤;只需將ISSUE
行的bind
字改爲:wrap
;然後嘗試類似:isText("bite me!");
你會看到指定類似的錯誤:
無法讀取未定義的屬性 「文本」 ..
左右;如果您在該函數定義中執行console.log(this)
;你會看到undefined
。
如果有人可以幫助解決這個,或者至少解釋爲什麼發生這種情況,我會很感激輸入。
@Kashif ::'wrap()'方法可以從閉包訪問屬性-external。它縮短了所需的代碼。 – argon
@deceze ::所有的代碼可能是問題的一部分;和 - 代碼是可用的,就像它,只是複製+粘貼& test;什麼都不是「失蹤」。 – argon
似乎您遇到的問題與您正在嘗試修復的問題相同。包裝好的isX函數不能從封裝的閉包中訪問'this'。我懷疑你實際上是在詢問你的「奇怪」的解釋 – Tibrogargan