typeof,constructor,hasOwnProperty,instanceof ,isPrototypeOf等名词解释

typeof

返回一个用来表示表达式的数据类型的字符串。

typeof[()expression[]] ;

expression 参数是需要查找类型信息的任意表达式。

说明

typeof 运算符把类型信息当作字符串返回。typeof 返回值有六种可能: "number," "string," "boolean," "object," "function," 和 "undefined."

typeof 语法中的圆括号是可选项。

typeof在以下两种情况下返回undefined

1.变量没有被声明

2.变量的值是undefined

console.log(typeof  test);//'undefined'

console.log(typeof undefined); //'undefined'

当typeof 后的表达式是null时:

console.log(typeof null); // 'object'

constructor

定义:constructor 属性返回对创建此对象的数组函数的引用

例1:

var test=new Array();

if(test.constructor==Array){

    console.log(‘这是数组’);

}

//这是数值

例2:

function employee(name){

    this.name=name

};

var bill=new employee('bill');

console.log(bill.constructor);

console.log(bill.constructor==employee);

//function employee(name){

    this.name=name

};

//true

例3:

function Person(){}

Person.prototype.name='Bill';

Person.prototype.sayName=function(){alert(this.name)}

var person=new Person();

console.log(person.constructor);//function Person(){}

如果将prototype改为字面量形式,结果将发生变化:

Person.prototype={

name:'Bill',

sayName:function(){alert(this.name)

}

console.log(person.constructor);//function Object() { [native code] }

没创建一个函数,就会同时创建它的prototype对象,这个对象会自动获得constructor属性,使用上面的语法本质上重写了默认的prototype对象,因此constructor属性也就改变成了新对象的constructor属性(指向Object构造函数),不再指向Person函数。如果真的需要constructor那么手动为constructor赋值:

Person.prototype={

constructor:Person, 

name:'Bill',

sayName:function(){alert(this.name)

}

instanceof 

用于判断一个变量是否某个对象的实例

instanceof 检测一个对象A是不是另一个对象B的实例的原理是:查看对象B的prototype指向的对象是否在对象A的[[prototype]]链上。如果在,则返回true,如果不在则返回false。不过有一个特殊的情况,当对象B的prototype为null将会报错(类似于空指针异常)。

例:

function Person(){};

Person.prototype={};

var person=new Person();

console.log(person instanceof  Person);//true

Person.prototype={};//相当于重写了prototype

console.log(person instanceof  Person);//false

Person.prototype=null;

console.log(person instanceof Person);//error

hasOwnProperty

hasOwnProperty是用来判断一个对象是否有你给出名称的属性或对象。此方法无法检查该对象的原型链中是否具有该属性,该属性必须是对象本身的一个成员。

isPrototypeOf 
isPrototypeOf
返回一个布尔值,该值指示对象是否存在于另一个对象的原型链中。

object1.isPrototypeOf(object2)

其中object1为必选项,一个对象的实例。

object2为必选项,另一个对象,将要检查其原型链。

posted on 2013-05-09 16:01  错河之泪  阅读(233)  评论(0编辑  收藏  举报