javascript中如何獲取對象名


javascript中如何獲取對象名

一、總結

一句話總結:將對象傳入參數,看參數是否為函數(js中的對象和函數是一個意思么(函數肯定是對象)),對象參數.name屬性即可獲得

//版本4 function getName(fun){ return typeof fun==='function'? undefined: fun.name||/function (.+)\(/.exec(fun + '')[1]; } //調用 function Person(){} var ps = new Person(); getName(ps.constractor); //通過獲取到constractor從而獲取到構造函數

 

 

 

二、JavaScript中獲取到對象名

我們經常要判斷用戶傳遞進來的對象名是不是合法的,那么我們就需要獲取到該對象的對象名,在chrome有提供直接獲取到對象名的方法,而在ie中就需要正則或者字符串切割,這么使用正則

//版本1
function getName(fun){
    if(typeof fun !== 'function')return;
    if(fun.name){
        return fun.name;
    }else{
        return /function (.+)\(/.exec(fun+'')[1];
    }
}

//版本2
function getName(fun){
    if(typeof fun !== 'function') return;
    return fun.name?fun.name:/function (.+)\(/.exec(fun+'')[1];
}

//版本3
function getName(fun){
    if(typeof fun!== 'function') return;
    return fun.name||/function (.+)\(/exec(fun + '')[1];
}

//版本4
function getName(fun){
    return typeof fun==='function'?
        undefined:
        fun.name||/function (.+)\(/.exec(fun + '')[1];
}
//調用
function Person(){}
var ps = new Person();
getName(ps.constractor);    //通過獲取到constractor從而獲取到構造函數

//很多框架中比較喜歡用版本4

 
參考:JavaScript中獲取到對象名 - CSDN博客
https://blog.csdn.net/qq_25956141/article/details/79156709
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM