JavaScript的构造器与对象(二)

constructor 的用法:对象的构造函数  每一个函数的Prototype属性指向的对象都包含唯一一个不可枚举属性constructor,该属性的值是这么一个对象:它指向了它所在的构造函数。
语法:Object.constructor 
 
确定一个对象是从哪里构造出来的。
1、常见的对象的构造器是
Number.constructor
=》Function() { [native code] }  数字的构造器是一个函数
var a=1 ;
a.contructor =>function Number()
2、类型检测
1、typeof
typeof 1
"number"
var a={};
typeof a
"object"
function a(){}
typeof a;
"function"
typeof true
"boolean"
typeof 是一个一元运算,放在一个运算数之前,运算数可以是任意类型。
它返回值是一个字符串,该字符串说明运算数的类型。typeof 一般只能返回如下几个结果:
number,boolean,string,function,object,undefined。我们可以使用 typeof 来获取一个变量是否存在,如 if(typeof a!="undefined"){alert("ok")},而不要去使用 if(a) 因为如果 a 不存在(未声明)则会出错,对于 Array,Null 等特殊对象使用 typeof 一律返回 object,这正是 typeof 的局限性
2、 instanceof 
     instanceof 用于判断一个变量是否某个对象的实例,如 var a=new Array();alert(a instanceof Array); 会返回 true,同时 alert(a instanceof Object) 也会返回 true;这是因为 Array 是 object 的子类。再如:function test(){};var a=new test();alert(a instanceof test) 会返回
 
3、对象工厂的方式来创建对象
function PersonFactory(pname,page)
    {
        return {
            name:pname,
            age:page,
        }
    }
    var p1 = PersonFactory("chen",22);
    var p2 = PersonFactory("CHEN",23);
    p1.name
    "chen"
    p2.name
    "CHEN"
4、function Person () {} //this
var p =new Person()  当把一个函数当成一个类来使用首字母大写;
那种就是constructh函数
在函数体内直接写var age = 20  在外面是访问不了。需要使用this来添加this.name
原文地址:https://www.cnblogs.com/chenjinxinlove/p/5199246.html