简体   繁体   English

如何检查命名空间是否存在?

[英]How to check if a namespaced function exists?

Is there a way to find out if a function in a namespace exists? 有没有办法找出名称空间中的函数是否存在? I'm trying to get the attribute value of an HTML element and then checking if the string value has a corresponding JavaScript function. 我正在尝试获取HTML元素的属性值,然后检查字符串值是否具有相应的JavaScript函数。

<a id="myLink" href="http://stackoverflow.com/" data-success-callback="$.Namespace.SomeFunction" />

var successCallback = $('#myLink').data('success-callback');

I know I can use typeof window[callback] === 'function' to check for functions declared globally but this doesn't seem to work with functions in a namespace; 我知道我可以使用typeof window [callback] ==='function'来检查全局声明的函数,但这似乎不适用于名称空间中的函数; it's undefined. 它是未定义的。

Is there a way to handle this? 有办法解决吗?

Thank you :) 谢谢 :)

Assuming callback is your successCallback object doing window[callback] === 'function' will only check that there is an object called '$.Namespace.SomeFunction ' at the root of the window object. 假设回调是您的successCallback对象,它执行window [callback] ==='function'只会检查窗口对象的根是否有一个名为'$ .Namespace.SomeFunction '的对象。 But what you want to achieve is to check if there is an object called SomeFunction in the object Namespace itself contained within the $ object. 但是,您要实现的是检查$对象中包含的对象名称空间本身中是否存在名为SomeFunction的对象。

To do so you can either use what @rps wrote aka typeof typeof myNamespace.myFunc if you already know the namespace and the function or use the below function that will traverse an object and look for a given path, in your case $.Namespace.SomeFunction : 为此,如果您已经知道名称空间和函数,则可以使用@rps编写的typeof typeof myNamespace.myFunc,也可以使用下面的函数来遍历对象并查找给定的路径(在本例中为$ .Namespace)。 SomeFunction:

var get = function (model, path, def) {
    path = path || '';
    model = model || {};
    def = typeof def === 'undefined' ? '' : def;
    var parts = path.split('.');
    if (parts.length > 1 && typeof model[parts[0]] === 'object') {
      return get(model[parts[0]], parts.splice(1).join('.'), def);
    } else {
      return model[parts[0]] || def;
    }
  } 

and now do something like 现在做类似的事情

typeof get(window, '$.Namespace.SomeFunction', 'undefined') === 'function'

I used this instead: 我改用这个:

function getProperty(objName) {
    var parts = objName.split('.');
    for (var i = 0, length = parts.length, obj = window; i < length; ++i) {
        obj = obj[parts[i]];
    }
    return obj;
}

Got it here: Access namespaced javascript object by string name without using eval 在这里得到它: 通过字符串名称访问命名空间的javascript对象,而无需使用eval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM