Chinaunix首页 | 论坛 | 博客
  • 博客访问: 40987
  • 博文数量: 30
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 310
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-10 07:50
个人简介

学会总结,积累

文章分类

全部博文(30)

文章存档

2014年(14)

2013年(16)

我的朋友

分类: JavaScript

2014-02-19 14:57:14

运算符

1) instanceof

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

语法:object instaceof constructor

说明: instanceof  操作符返回一个布尔值,检测 object 是否是 constructor 的一个实例(直面翻译是检测 object 的原型链中是否存在 constructor的原型--不知道我这样说对不对)
举例:
function A(){
    this.a=[];
}
function B(){
    this.b = {}
}
B.prototype = new A();
var b = new B();
console.log(b instanceof B);//true
console.log(b instanceof A);//true

2) typeof

The typeof operator returns a string indicating the type of the unevaluated operand.

语法:typeof operand
说明: typeof 运算符返回一个字符串,这个字符串说明 operand的类型,如果operand是未定义的,则返回'undefined'(也是字符串)
举例:
typeof undefined // 'undefined';
typeof
blabla //'undefined';an undefined variable
typeof function(){} // 'function';
typeof Math.sin // 'function';
typeof {a:1} // 'object';
typeof [1, 2, 4] // 'object'

方法

1) isArray()

The Array.isArray() method returns true if an object is an array, false if it is not.


2) Object.prototype.toString(.call | .apply)

在中,Object.prototype.toString方法的规范如下:

15.2.4.2 Object.prototype.toString()

toString方法被调用时,会执行下面的操作步骤:

1. 获取this对象的[[Class]]属性的值.

2. 计算出三个字符串"[object ", 第一步的操作结果Result(1), 以及 "]"连接后的新字符串.

3. 返回第二步的操作结果Result(2).

[[Class]]是一个内部属性,所有的对象(原生对象和宿主对象)都拥有该属性.在规范中,[[Class]]是这么定义的: 一个字符串值,表明了该对象的类型. 也就是说,把Object.prototype.toString方法返回的字符串,去掉前面固定的"[object "和后面固定的"]",就是内部属性[[class]]的值,也就达到了判断对象类型的目的.jQuery中的工具方法$.type(),就是干这个的.

在ES3中,规范文档并没有总结出[[class]]内部属性一共有几种,不过我们可以自己统计一下,原生对象的[[class]]内部属性的值一共有10种.分别是:"Array", "Boolean", "Date", "Error", "Function", "Math", "Number", "Object", "RegExp", "String".

3) constructor

object.constructor 返回对象的构造函数
function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}

var bill=new employee("Bill Gates","Engineer",1985);

document.write(bill.constructor === Function); //false
document.write('
');
document.write(typeof bill); //object
document.write('
');
document.write(bill.constructor); //function employee(name,job,born) { this.name=name; this.job=job; this.born=born; }



阅读(357) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~