Re: [問題] 在Function中取得Function Name
※ 引述《IwillSay (我將會)》之銘言:
: 請問假如我有一個object長這樣
: var fns = {
: MethodA : function() {
: //alert(???); 在這邊取得MethodA的字串
: }
: };
: 請問有辦法在MethodA裡面取得他對應的Property Name嗎(MethodA)
var fns = {
a1 : 123,
a2 : 456,
a3 :"xxx",
Method1 : function() {
alert(this.a1);
},
MethodA : function (){
var name;
for (name in this) {
if (this.hasOwnProperty(name) && typeof this[name] === 'function' &&
arguments.callee === this[name]) {
break;
}
}
alert(name);
},
Method2 : function() {
alert(this.a2);
}
};
fns.Method1();
fns.Method2();
fns.MethodA();
http://www.jsfiddle.net/5E4eq/8/
先用for 循環this
由於for in 會讀取所有prototype chain 上的 property
所以用hasOwnProperty過濾
並用typeof 只讀取function
最後再比對是不是同一個function object
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.59.14.51
※ 編輯: sk1765 來自: 61.59.14.51 (02/10 22:24)
推
02/10 23:15, , 1F
02/10 23:15, 1F
→
02/10 23:22, , 2F
02/10 23:22, 2F
→
02/10 23:23, , 3F
02/10 23:23, 3F
推
02/10 23:26, , 4F
02/10 23:26, 4F
推
02/10 23:31, , 5F
02/10 23:31, 5F
→
02/10 23:44, , 6F
02/10 23:44, 6F
→
02/10 23:52, , 7F
02/10 23:52, 7F
→
02/10 23:53, , 8F
02/10 23:53, 8F
推
02/11 00:42, , 9F
02/11 00:42, 9F
推
02/11 00:55, , 10F
02/11 00:55, 10F
推
02/11 01:02, , 11F
02/11 01:02, 11F
→
02/11 01:02, , 12F
02/11 01:02, 12F
推
02/11 01:22, , 13F
02/11 01:22, 13F
推
02/11 02:25, , 14F
02/11 02:25, 14F
→
02/11 02:26, , 15F
02/11 02:26, 15F
推
02/11 07:27, , 16F
02/11 07:27, 16F
→
02/11 08:10, , 17F
02/11 08:10, 17F
推
02/12 00:02, , 18F
02/12 00:02, 18F
推
02/12 00:15, , 19F
02/12 00:15, 19F
推
02/12 00:18, , 20F
02/12 00:18, 20F
→
02/12 00:18, , 21F
02/12 00:18, 21F
→
02/12 00:19, , 22F
02/12 00:19, 22F
→
02/12 00:19, , 23F
02/12 00:19, 23F
→
02/12 00:20, , 24F
02/12 00:20, 24F
討論串 (同標題文章)
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章