类型系统

2015-08-13  本文已影响85人  洗阳光

基本类型

primitive types

<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a>

typeof

<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString">Object.prototype.toString</a>

Object.prototype.toString

<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor">constructor</a>

constructor

<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof">instanceof</a>

instanceof

实现type函数用于识别标准类型和内置对象类型,语法如下:

var t = type(obj);

使用举例如下:

var t = type(1) // t==="number"
var t = type(new Number(1)) // t==="number"
var t = type("abc") // t==="string"
var t = type(new String("abc")) // t==="string"
var t = type(true) // t==="boolean"
var t = type(undefined) // t==="undefined"
var t = type(null) // t==="null"
var t = type({}) // t==="object"
var t = type([]) // t==="array"
var t = type(new Date) // t==="date"
var t = type(/\d/) // t==="regexp"
var t = type(function(){}) // t==="function"

代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>typeof</title>
    <script>
        var type= function (a){
            var t = Object.prototype.toString.call(a);
            t = t.slice(8,16);
            for (var i = 0; i < t.length; i++) 
            {
                if (t[i]=="]") {
                    t= t.slice(0,t.length-1)
                };
            };
            alert(t);
        };
    </script>
</head>
<body>
上一篇 下一篇

猜你喜欢

热点阅读