Blogger Information
Blog 48
fans 0
comment 0
visits 40342
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0911-js对象的生成
3期-Shawn的博客
Original
738 people have browsed it

编程: 创建对象的方式(字面量或构造函数)

实例

<title>JavaScript基本语法与实例</title>
<meta charset="utf-8">
<!-- type="text/javascript"但考虑到js是前端唯一并且是默认脚本,所以推荐省略掉-->
<script type="text/javascript">//<script>中引入外部脚本时src="js.js",其标签内的js代码将会被忽略.
//let site = 'php中文网'; 
//alert(site);//弹窗显示
//document.write(site);//文本显示
//console.log(site);//控制台显示


//创建对象的方式

//字面量创建
 var obj = {name:'wang', age:29};
 document.write(obj.name+'<br>');
  document.write(obj.age+'<hr>');

  function getData(x, y, z) 
  {
     return (x+y+z);
  }
  document.write(getData(1,2,3)+'<hr>');


  function getData1(data) 
  {
     return (data.x+data.y+data.z)
  }
  document.write(getData1({x:4, y:5, z:6})+'<hr>');



  function getData2(data) 
  {
                //函数内修改参数值并不是一个好习惯
     data = data || {x:1, y:2, z:3};
     return (data.x+data.y+data.z);
  }
  document.write(getData2()+'<hr>');



  function func() 
  {
     return {x:4, y:5, z:6}
  }
  document.write(func()+'<hr>');



  function func1() 
  {
     return [4, 5, 6]
  }
            
  document.write([x,y,z]=func1()+'<hr>'); 
 //构造函数创建
 function createObj() 
  {
                //直接将对象字面量做为返回值
     return {
              x: 10,
              y: 20,
              z: 30,
              sum: function () 
              {
                return this.x + this.y + this.z;
              }
            }
 }
 var obj = createObj();
 document.write(obj.x+'<br>');
 document.write(obj.sum()+'<hr>'); 



 function MyClass(x, y) 
 {
     this.x = x;
     this.y = y;
 }
 var obj1 = new MyClass(10,20);
 document.write(obj1.x+'<hr>');
             

  

</script>

运行实例 »

点击 "运行实例" 按钮查看在线实例

0911zuoye1.png

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post