typeof、instanceof与hasOwnProperty

typeof

ECMAScript是松散类型的,所谓松散类型及时可以用来保存任何类型的数据,因此需要一种手段来检查特定的数据类型。typeof就是用来提供这方面信息的操作符。ECMAScript有5种简单数据类型(也称基本数据类型):Undefined,Null,Boolean,Number和String。还有一种复杂数据类型Object。对一个值使用typeof检测可能返回下列6个字符串,但却不是一一对应的关系。

  • “undefined” ————如果这个值未定义,或者声明了但没有赋值。
  • “boolean” ———— 如果这个值是布尔值
  • “string” ————如果这个值是字符串
  • “number” ————如果这个值是数字
  • “object” ————如果这个值是对象或者null
  • “function” ———— 如果这个值是函数

instanceof

insatnceof 运算符用来检测一个对象在其原型链中是否存在一个构造函数的prototype属性。
语法为: object instanceof constructor

var arr =new Array(); console.log(arr instanceof test ) //true console.log(arr instanceof Object) //也会返回true,因为Array是Object的子类

hasOwnProperty

hasOwnProperty()方法可以用来检测一个属性是存在实例中,还是存在原型中。

function Person(){} Person.prototype.name = "Jessica"; Person.prototype.age =25; var person = new Person(); console.log(person.hasOwnProperty("name")) //false person.name ="Anna"; console.log(person.hasOwnProperty("name")) //true

猜你喜欢

转载自www.cnblogs.com/JessicaIsEvolving/p/9132777.html
今日推荐