Javascript angular.isDefined() 与 obj.hasOwnProperty()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26219073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
angular.isDefined() vs obj.hasOwnProperty()
提问by user3040068
I have an object that may or may not have a status. When using the angular.js framework which would be more appropriate. What are the advantages and disadvantages of both.
我有一个可能有状态也可能没有状态的对象。使用 angular.js 框架时哪个更合适。两者各有什么优缺点。
var checkStatus = function(item){
if(angular.isDefined(item.status){
//do something
}
//VS.
if(item.hasOwnProperty('status')){
//do something
}
}
checkStatus(item);
回答by Cétia
angular.isDefinedonly test if the value is undefined:
angular.isDefined仅测试该值是否为undefined:
function isDefined(value){return typeof value !== 'undefined';}
Object.hasOwnPropertytest if the value is a direct one and not an inherited one.
Object.hasOwnProperty测试该值是否是直接值而不是继承值。
For example :
例如 :
var test = {};
angular.isDefined(test.toString); // true
test.hasOwnProperty('toString'); // false
信息:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

