首页 > 语言 > JavaScript > 正文

判断js中各种数据的类型方法之typeof与0bject.prototype.toString讲解

2024-05-06 14:34:12
字体:
来源:转载
供稿:网友

1、typeof(param) 返回param的类型(string)

这种方法是JS中的定义的全局方法,也是编译者们最常用的方法,优点就是使用简单、好记,缺点是不能很好的判断object、null、array、regexp和自定义对象。

示例代码:
代码如下:
var str='str';
var arr=['1','2'];
var num=1;
var bool=true;
var obj={name:'test'};
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;

function fn(){
    alert('this is a function');
}

function User(name){
    this.name=name;
}
var user=new User('user');

console.log(typeof(str));
console.log(typeof(arr));
console.log(typeof(num));
console.log(typeof(bool));
console.log(typeof(obj));
console.log(typeof(nullObj));
console.log(typeof(undefinedObj));
console.log(typeof(reg));
console.log(typeof(fn));
console.log(typeof(user));

结果为:
代码如下:
string
object
number
boolean
object
object
undefined
object
function
object

2、Object.prototype.toString().call(param) 返回param的类型(string,格式是[object class])

这个方法能支持绝大多数类型的判断,jquery封装的类型判断就用的这个方法。可能有些人看起来有点迷茫,我来给大家分解一下。

1)call(param)函数

a.fun().call(b)的意思在js中是指,让对象b来代替a,然后执行a的fun函数,写个例子:
代码如下:
function Class1()
{
    this.name = "class1";

    this.showNam = function()
    {
        alert(this.name);
    }
}

function Class2()
{
    this.name = "class2";
}

var c1 = new Class1();
var c2 = new Class2();

c1.showNam.call(c2);

运行结果,输出的为class2,而不是class1,这就相当于是方法继承。
所以,Object.prototype.toString().call(param)的意思其实就是,param.prototype.toString(),那么我们为什么不直接写param.prototype.toString(),而是用call()绕一下呢,下面请看2来了解。

2)Object.prototype.toString()

Object是个什么东东呢?,Script56.chm(就是M$官方教程)上说:Obect提供所有 JScript对象通用的功能,其实Object就是所有js对象的祖先,是一个概念,js中的所有对象就是Object的实例,然后不同的对象重写自己独立的方法。而prototype,大家就没必要追究太深了,它就是返回一个原型的引用,然可以可以动态的给原型添加方法和属性
一个小例子
代码如下:
function class(){
  this.name = "class";
  this.showName = function(){
    alert(this.name);
  }
}
var obj = new class();
obj.showName();
class.prototype.showNameContact = function(){
  alert("prototype test"+this.name);

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选