检查某对象是否有某属性
当你需要检查某属性是否存在于一个对象,你可能会这样做:
var myObject = {
name: '@tips_js'
};
if (myObject.name) { ... }
这是可以的,但是你需要知道有两种原生方法可以解决此类问题。in
操作符 和 Object.hasOwnProperty
,任何继承自Object
的对象都可以使用这两种方法。
看一下较大的区别
var myObject = {
name: '@tips_js'
};
myObject.hasOwnProperty('name'); // true
'name' in myObject; // true
myObject.hasOwnProperty('valueOf'); // false, valueOf 继承自原型链
'valueOf' in myObject; // true
两者检查属性的深度不同,换言之hasOwnProperty
只在本身有此属性时返回true,而in
操作符不区分属性来自于本身或继承自原型链。
这是另一个例子
var myFunc = function() {
this.name = '@tips_js';
};
myFunc.prototype.age = '10 days';
var user = new myFunc();
user.hasOwnProperty('name'); // true
user.hasOwnProperty('age'); // false, 因为age来自于原型链
在线示例!
同样建议阅读关于检查对象是否包含属性时常见错误的讨论。
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW