zoukankan      html  css  js  c++  java
  • JS对象与构造函数

    普通对象与函数对象

    JavaScript 中,万物皆对象!但对象也是有区别的,分为普通对象和函数对象,Object 、Function 是 JS 自带的函数对象。下面举例说明

    var o1 = {}; 
    var o2 =new Object();
    var o3 = new f1();
    function f1(){};
    var f2 = function(){};
    var f3 = new Function('str','console.log(str)');
    console.log(typeof Object); //function
    console.log(typeof Function);//function  
    console.log(typeof f1);//function  
    console.log(typeof f2);//function  
    console.log(typeof f3); //function
    console.log(typeof o1);//function  
    console.log(typeof o2); //object
    console.log(typeof o3); //object

    在上面的例子中 o1 o2 o3 为普通对象,f1 f2 f3 为函数对象。

    怎么区分,其实很简单,凡是通过 new Function() 创建的对象都是函数对象,其他的都是普通对象。

    f1,f2,归根结底都是通过 new Function()的方式进行创建的。Function Object 也都是通过 New Function()创建的。

    构造函数

    function Person(name, age, job) { 
    this.name = name;
    this.age = age;
    this.job = job;
    this.sayName = function() {
    alert(this.name)
    }
    }
    var person1 = new Person('Zaxlct', 28, 'Software Engineer');
    var person2 = new Person('Mick', 23, 'Doctor');

    上面的例子中 person1 和 person2 都是 Person 的实例。这两个实例都有一个constructor(构造函数)属性,该属性(是一个指针)指向 Person。 即:

    console.log(person1.constructor == Person); //true
    console.log(person2.constructor == Person); //true

    我们要记住两个概念(构造函数,实例):person1 和 person2 都是 构造函数 Person 的实例,一个公式:实例的构造函数属性(constructor)指向构造函数。

  • 相关阅读:
    spoj 3273 Treap
    hdu1074 Doing Homework
    hdu1024 Max Sum Plus Plus
    hdu1081 To the Max
    hdu1016 Prime Ring Problem
    hdu4727 The Number Off of FFF
    【判断二分图】C. Catch
    【01染色法判断二分匹配+匈牙利算法求最大匹配】HDU The Accomodation of Students
    【数轴涂色+并查集路径压缩+加速】C. String Reconstruction
    【数轴染色+并查集路径压缩+加速】数轴染色
  • 原文地址:https://www.cnblogs.com/hello9102/p/12840149.html
Copyright © 2011-2022 走看看