zoukankan      html  css  js  c++  java
  • javascript创建对象

    JavaScript中对象的创建有以下几种方式: 

    (1)使用内置对象 
    (2)使用JSON符号 
    (3)自定义对象构造 

    一、使用内置对象 

    JavaScript可用的内置对象可分为两种: 
    1,JavaScript语言原生对象(语言级对象),如String、Object、Function等; 
    2,JavaScript运行期的宿主对象(环境宿主级对象),如window、document、body等

    var str = new String("实例初始化String"); 
    var str1 = "直接赋值的String"; 
    var func = new Function("x","alert(x)");//示例初始化func 
    var o = new Object();//示例初始化一个Object 
    window.onload=function(){
                var arr=new Array();
                var colors = new Array("ds","dsddd");
                var str=new String("fds");
            console.log(str)
            
    }

    输出:String {0: "f", 1: "d", 2: "s", length: 3, [[PrimitiveValue]]: "fds"}

    二、自定义对象构造 

    创建高级对象构造有两种方式:使用“this”关键字构造、使用原型prototype构造

    //使用this关键字定义构造的上下文属性 
    function Girl() 
    { 
    this.name = "big pig"; //用this关键字
    this.age = 20; 
    this.standing; 
    this.bust; 
    this.waist; 
    this.hip; 
    } 
    
    //使用prototype 
    function Girl(){} 
    Girl.prototype.name = "big pig"; 
    Girl.prototype.age = 20; 
    Girl.prototype.standing; 
    Girl.prototype.bust; 
    Girl.prototype.waist; 
    Girl.prototype.hip; 
    alert(new Girl().name); 

    //使用工厂函数
     function Car(color,door){ 
      var ocar = new Object; //利用对象来创建
      ocar.color = color; 
      ocar.doors = door; 
      ocar.showColor = function(){ 
      document.write(this.color) 
      }; 
      return ocar; 
      } 
    var car1 = Car("red",4); 

    封装js工具类

    <<愿你被这世界温柔以待...>>
  • 相关阅读:
    实验一 命令解释程序的编写
    试验二
    实验一 命令解释程序的编写(重交)
    Sqlserver数据库帮助类(EFTools)
    js验证
    sqlserver中从日期字段取得月份
    IIS不可用或者有问题解决方法
    professional email address collections
    从psd文件到html
    空白符对HTML结构的影响与解决方案
  • 原文地址:https://www.cnblogs.com/NotePad-chen/p/7345018.html
Copyright © 2011-2022 走看看