前言
本文记录Javascript在html文件中创建对象的3种方式,主要是为了增加对js的认识!从而实现APP混编的目的!本文可关联以下文章进行学习!
本文的学习过程
- 普通对象创建法
- Object创建法
- Json格式实例化对象
1.普通对象创建法
function student(name,age){ this.name = name; this.age = age; student.gender = 'male'; this.info = function(){ document.write("名字:"+this.name+",年龄"+this.age+",性别:"+student.gender); } } //实例化对象 var s1 = new student('zhangsan',30); //执行info方法 s1.info();
2.Object创建法
//实例化对象 var student = new Object(); //设置对象属性&&方法 student.name = 'zhangsan'; student.age = 30; student.info = function(){ document.write("名字:"+this.name+",年龄"+this.age+",性别:"+student.gender); } //对象调用方法 student.info();
3.Json格式实例化对象
var person ={ "name":"zhangsan", "age":30, // 'gender':'male', "son":[ { "name":"jack", "age":2 },{ "name":"rose", "age":3 } ], "info":function(){ document.write("名字:"+this.name+",年龄"+this.age+",性别:" +"<br/>"); for(var child in this.son){ document.write("名字:"+this.son[child].name+",年龄"+this.son[child].age+",性别:" +"<br/>"); } } }; //调用对象方法 person.info();
第三种方法对我们来说就是一个JSON格式的字符串
html文件全貌
<!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> //创建对象有三种方式 //普通对象创建法 /* function student(name,age){ this.name = name; this.age = age; student.gender = 'male'; this.info = function(){ document.write("名字:"+this.name+",年龄"+this.age+",性别:"+student.gender); } } var s1 = new student('zhangsan',30); s1.info(); */ //第二种对象生成方式 /* var student = new Object(); student.name = 'zhangsan'; student.age = 30; student.info = function(){ document.write("名字:"+this.name+",年龄"+this.age+",性别:"+student.gender); } student.info(); */ // 第三种方式: 使用json格式来是例化对象 var person ={ "name":"zhangsan", "age":30, // 'gender':'male', "son":[ { "name":"jack", "age":2 },{ "name":"rose", "age":3 } ], "info":function(){ document.write("名字:"+this.name+",年龄"+this.age+",性别:" +"<br/>"); for(var child in this.son){ document.write("名字:"+this.son[child].name+",年龄"+this.son[child].age+",性别:" +"<br/>"); } } }; //调用对象方法 person.info(); </script> </head> <body> <div>TODO write content</div> </body> </html>
总结:
本文描述了Js创建对象的3种方法,这些JS的代码学习,对我们APP混合设计非常重要。在与前端交互的时候,我们可以将需要的js代码注入到前端的html文件去。