如果给定的变量名称已经由 javascript 引擎或浏览器定义,我需要一个函数来返回 true。
例如
isNative('window') //true;
isNative('Math') //true;
isNative('myVar') //false
isNative('navigator') //true
isNative('document') //true
如果给定的变量名称已经由 javascript 引擎或浏览器定义,我需要一个函数来返回 true。
例如
isNative('window') //true;
isNative('Math') //true;
isNative('myVar') //false
isNative('navigator') //true
isNative('document') //true
好的,我找到了解决方案。
function isNative(variableName) {
if (window['__emptyIframeRef__'] === undefined) {
window['__emptyIframeRef__'] = document.createElement('iframe');
window['__emptyIframeRef__'].setAttribute('style', 'display:none');
document.getElementsByTagName('body')[0].appendChild(window['__emptyIframeRef__']);
}
return window['__emptyIframeRef__'].contentWindow[variableName] !== undefined;
}
我不认为这是你想要的。第一件事;全局变量不好。因此,您应该拥有自己的命名空间,在其中拥有所有自己的逻辑/模块/功能;
var danial={
module1:{
get:function(bla){...}
},
module2:(function(){
....
}());
}
现在,本机对象/函数和自定义对象/函数之间没有区别。它们都有对象原型在原型链之上,没有办法区分。但是,您可以检查的内容是,如果您的对象本身具有属性,或者它是否在原型链上“继承”,例如 toString 将始终存在但不属于您的对象(除非您已定义并覆盖它)。您可以使用以下代码进行检查
for (var prop in obj) {
if( obj.hasOwnProperty( prop ) ) {
console.log("own property", prop, obj[prop]);
}
}
这是可能的,但我不知道你能做些什么,而且效率也不高。
您需要做的就是首先准备一个变量来克隆窗口。
// Borrowed from Coffeescript
// Similar functionality as underscore.js extend()
__extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype; child.prototype = new ctor();
child.__super__ = parent.prototype; return child;
};
var foo;
foo = __extends({}, window);
//Usage
foo.hasOwnProperty('console')
// true
window.hasOwnProperty('console')
// true
var bar = 'bar'
foo.hasOwnProperty('bar')
// false
window.hasOwnProperty('bar')
// true
function isNative(variableName){
return window[variableName]!=undefined;
}
alert(isNative('window')) //true;
alert(isNative('Math')) //true;
alert(isNative('myVar')) //false
alert(isNative('navigator')) //true
alert(isNative('document')) //true
'document' 对象虽然不是原生的。
function isNative(variableName){
return [Object,Function,Array,String,Boolean,Number,Date,RegExp,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].some(function(element){return window[variableName]===element});
}
myVar = 10;
alert(isNative('Object')) //true;
alert(isNative('String')) //true;
alert(isNative('myVar')) //false;
alert(isNative('document')) //false;
检查它是否可以帮助您:http: //jsfiddle.net/na65y/2/