面向对象(二)

Object.prototype.toString

在 JavaScript 里使用 typeof 来判断数据类型,只能区分基本类型,即 “number”,”string”,”undefined”,”boolean”,”object” 五种。

对于数组、函数、对象来说,其关系错综复杂,使用 typeof 都会统一返回 “object” 字符串。

要想区别对象、数组、函数单纯使用 typeof 是不行的,JavaScript中,通过Object.prototype.toString方法,判断某个对象值属于哪种内置类型。

由于 JavaScript 中一切都是对象,任何都不例外,对所有值类型应用 Object.prototype.toString.call() 方法结果如下:

Object.prototype.toString.call()方法浅谈
使用Object.prototype上的原生toString()方法判断数据类型,使用方法如下:

Object.prototype.toString.call(value)
1.判断基本类型:

1
2
3
4
5
Object.prototype.toString.call(null);//”[object Null]”
Object.prototype.toString.call(undefined);//”[object Undefined]”
Object.prototype.toString.call(“abc”);//”[object String]”
Object.prototype.toString.call(123);//”[object Number]”
Object.prototype.toString.call(true);//”[object Boolean]”

2.判断原生引用类型:
函数类型

1
2
Function fn(){console.log(“test”);}
Object.prototype.toString.call(fn);//”[object Function]”

日期类型

Function fn(){console.log(“test”);}
Object.prototype.toString.call(fn);//”[object Function]”

数组类型

var arr = [1,2,3];
Object.prototype.toString.call(arr);//”[object Array]”

正则表达式

var reg = /[hbc]at/gi;
Object.prototype.toString.call(arr);//”[object Array]”

自定义类型

function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("Rose", 18);
Object.prototype.toString.call(arr); //”[object Object]”
很明显这种方法不能准确判断person是Person类的实例,而只能用instanceof 操作符来进行判断,如下所示:
console.log(person instanceof Person);//输出结果为true

3.判断原生JSON对象:

1
2
var isNativeJSON = window.JSON && Object.prototype.toString.call(JSON);
console.log(isNativeJSON);//输出结果为”[object JSON]”说明JSON是原生的,否则不是;

constructor

我们知道,默认情况下,对一个函数前面使用new,可以构造出一个对象。每一个对象都有一个constructor属性,这个constructor属性指向构造出该对象的函数。

这个属性是理解JavaScript类和继承的重要基础
实例化对象.constructor = 实例化对象的构造函数
注意:不是100%准确,容易被修改。

1
2
3
4
5
6
7
8
9
10
11
// 等价于 var foo = new Array(1, 56, 34, 12); 
var arr = [1, 56, 34, 12];
console.log(arr.constructor === Array); // true
// 等价于 var foo = new Function();
var Foo = function() { };
console.log(Foo.constructor === Function); // true
// 由构造函数实例化一个obj对象
var obj = new Foo();
console.log(obj.constructor === Foo); // true
// 将上面两段代码合起来,就得到下面的结论
console.log(obj.constructor.constructor === Function); // true

请我吃辣条吧~~
-------------本文结束感谢您的阅读-------------