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工具类

 

posted @ 2017-08-11 11:26  NotePad_chen  阅读(177)  评论(0编辑  收藏  举报