javascript对象的理解
从代码中体会javascript中的对象:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js demo</title> <script type="text/javascript" charset="utf-8"> // 定义一个方法,这样只有触发事件调用 function myFunction() { var person = { fname: "Bill", lname: "Gates", age: 56, // 理解为Java对象里面的静态方法和属性,所以不用实例化就可以访问获取 setFname:function(name) { this.fname = name; console.info(this.fname); } }; console.info(person); // 定义一个数组 var persons = new Array(); person.setFname("Guxingzhe") persons.push(person); persons.push(person); persons.push(person); console.info(persons); function User(name,age){ contry = "China";//私有不可访问 this.name = name;//公有可以访问(判断是否带this) this.age = age; this.canFly = false; this.eat = function() { console.info("吃饭"); } } // 通过原型函数,继承覆盖toLocaleString方法 User.prototype.toLocaleString = function(){ return this.name + ":" + this.age + ":" + this.canFly; }; var user=new User(); user.eat(); console.info(user); console.info ((user.name="guxingzhe") + ":" + (user.age=12) + ":" + user.canFly); var users = new Array(); users.push(new User("guxingzhe1", 12)); users.push(new User("guxingzhe2", 12)); users.push(new User("guxingzhe3", 12)); console.info(users.toLocaleString());//类似java里面的toString for(var i = 0; i < users.length; i++) { console.info(users[i].name); } } // 定义一个小车对象,里面有属性及方法 // 本人理解为Java中对象里定义类静态方法,所以可以直接访问不用实例化在访问属性 var car = { pointX:10, pointY:100, run:function() { console.info("run method"); }, stop:function() { console.info("stop method"); }, start:function() { console.info("start method"); }, point:function() { // 记得加this,不然会解析器认为是方法里面的属性,识别为未定义 console.info(this.pointX + ":" + this.pointY); } } car.run(); car.stop(); car.start(); car.point(); // 对象方法 function people(firstname, lastname, age, eyecolor) { this.firstname = firstname; this.lastname = lastname; this.age = age; this.eyecolor = eyecolor; } // 实例化一个对象方法 people = new people("John", "Doe", 50, "blue"); // 打印对象方法的属性 console.info(people.firstname + " is " + people.age + " years old."); </script> </head> <body> <button onclick="myFunction()">触发</button> </body> </html>
调试环境火狐+firebug.
运行效果如下: