zoukankan      html  css  js  c++  java
  • Javascript之基本包装类型

    一.基本包装类型概述

    var box = 'Mr. Lee';//定义一个字符串
    var box2 = box.substring(2);//截掉字符串前两位
    alert(box2);//输出新字符串


    变量 box 是一个字符串类型,而 box.substring(2)又说明它是一个对象(PS:只有对象才会调用方法),最后把处理结果赋值给 box2。

    'Mr. Lee'是一个字符串类型的值,按道理它不应该是对象,不应该会有自己的方法,比如:alert('Mr. Lee'.substring(2));//直接通过值来调用方法

    --------------------------------------

    1.字面量写法:

    var box = 'Mr. Lee';//字面量
    box.name = 'Lee';//无效属性
    box.age = function () {//无效方法
      return 100;
    };
    alert(box);//Mr. Lee
    alert(box.substring(2));//. Lee
    alert(typeof box);//string
    alert(box.name);//undefined
    alert(box.age());//错误


    2.new 运算符写法:

    var box = new String('Mr. Lee');//new 运算符
    box.name = 'Lee';//有效属性
    box.age = function () {//有效方法
      return 100;
    };
    alert(box);//Mr. Lee
    alert(box.substring(2));//. Lee
    alert(typeof box);//object
    alert(box.name);//Lee
    alert(box.age());//100

    以上字面量声明和 new 运算符声明很好的展示了他们之间的区别。但有一定还是可以肯定的,那就是不管字面量形式还是 new 运算符形式,都可以使用它的内置方法。并且Boolean 和 Number 特性与 String 相同,三种类型可以成为基本包装类型。

    PS:在使用 new 运算符创建以上三种类型的对象时,可以给自己添加属性和方法,但我们建议不要这样使用,因为这样会导致根本分不清到底是基本类型值还是引用类型值。

  • 相关阅读:
    POJ 1330 Nearest Common Ancestors(LCA Tarjan算法)
    LCA 最近公共祖先 (模板)
    线段树,最大值查询位置
    带权并查集
    转负二进制
    UVA 11437 Triangle Fun
    UVA 11488 Hyper Prefix Sets (字典树)
    UVALive 3295 Counting Triangles
    POJ 2752 Seek the Name, Seek the Fame (KMP)
    UVA 11584 Partitioning by Palindromes (字符串区间dp)
  • 原文地址:https://www.cnblogs.com/n2meetu/p/6139917.html
Copyright © 2011-2022 走看看