第四章 理解对象

1 说明

  对象的状态:属性,行为:方法;

  对象定义放在花括号内;

  用冒号分隔属性名和属性值;

  用逗号分隔属性名和属性值对,包括方法;

  最后一个属性值后面不加逗号;

  属性名可以是任何字符串,但通常遵循变量命名规则,包含空格时必须用引号将其括起来;

  同一个对象中不能包含两个同名的属性;

  句点表示法访问对象,当然也可以用方括号方法(更为灵活且需注意无逗号);

  添加新属性:指定新属性并赋值:fiat.needsWashing=true;

  删除属性:delete fido.dogYears;(删除成功返回true);

  创建一个无属性的对象: var lookMaNoProps={ };

  将对象信息显示到控制台: console.log(fiat);

  函数中传递的是对象的引用,因此在函数中对对象的修改有效;

2 实例1:

  1. <script language="JavaScript" type="text/JavaScript">
  2. function getSecret(file,secretPassword)
  3. {
  4. file.opened=file.opened+1;
  5. if(secretPassword==file.password)
  6. return file.contents;
  7. else
  8. return "Invalid password! No secret for you.";
  9. }
  10. function setScret(file,secretPassword,secret)
  11. {
  12. if(secretPassword==file.password)
  13. {
  14. file.opened=0;
  15. file.contents=secret;
  16. }
  17. }
  18. var superSecretFile={
  19. level:"classifiled",
  20. opened:0,
  21. password:2168,
  22. contents: "Dr. Evel's next meeting is in Detroit."
  23. };
  24. var secret=getSecret(superSecretFile,2168);
  25. console.log(secret);
  26. var secret1=getSecret(superSecretFile,2152);
  27. console.log(secret1);
  28. setScret(superSecretFile,2168,"Dr . Evel's next meeting is in Philadelphia");
  29. secret=getSecret(superSecretFile,2168);
  30. console.log(secret);
  31. </script>

3 实例2:

  1. <!doctype html>
  2.  
  3. <html lang="en">
  4.  
  5. <head>
  6.  
  7. <title>Battleship</title>
  8.  
  9. <meta charset="utf-8">
  10.  
  11. </head>
  12.  
  13. <body>
  14.  
  15. <script language="JavaScript" type="text/JavaScript">
  16.  
  17. function makeCar()
  18.  
  19. {
  20.  
  21. var makes=["Chevy","GM","Fiat","Webville Motors","Tucker"];
  22.  
  23. var models=["Cadillac","500","Bel-Air","Taxi","Torpedo"];
  24.  
  25. var years=[1955,1957,1948,1954,1961];
  26.  
  27. var colors=["red","blue","tan","yellow","white"];
  28.  
  29. var convertile=[true,false];
  30.  
  31. var rand1=Math.floor(Math.random()*makes.length);
  32.  
  33. var rand2=Math.floor(Math.random()*models.length);
  34.  
  35. var rand3=Math.floor(Math.random()*years.length);
  36.  
  37. var rand4=Math.floor(Math.random()*colors.length);
  38.  
  39. var rand5=Math.floor(Math.random()*5)+1;
  40.  
  41. var rand6=Math.floor(Math.random()*2);
  42.  
  43. var car={
  44.  
  45. make:makes[rand1],
  46.  
  47. model:models[rand2],
  48.  
  49. year:years[rand3],
  50.  
  51. color:colors[rand4],
  52.  
  53. passengers:rand5,
  54.  
  55. convertile:convertile[rand6],
  56.  
  57. mileage:0,
  58.  
  59. fuel:0,
  60.  
  61. started:false,
  62.  
  63. start:function(){
  64.  
  65. this.started=true;
  66.  
  67. },
  68.  
  69. stop:function(){
  70.  
  71. this.started=false;
  72.  
  73. },
  74.  
  75. drive:function(){
  76.  
  77. if(this.started)
  78.  
  79. {
  80.  
  81. if(this.fuel>0)
  82.  
  83. alert("Zoom zoom!");
  84.  
  85. else
  86.  
  87. {
  88.  
  89. alert("Uh , oh ,out of fuel!");
  90.  
  91. this.stop();
  92.  
  93. }
  94.  
  95. }
  96.  
  97. else
  98.  
  99. alert("You need to start the engine first!");
  100.  
  101. },
  102.  
  103. addFuel:function(amount){
  104.  
  105. this.fuel+=amount;
  106.  
  107. }
  108.  
  109. };
  110.  
  111. return car;
  112.  
  113. }
  114.  
  115. function displayCar(car)
  116.  
  117. {
  118.  
  119. console.log("Your new car is a "+car.year+" "+car.make+" "+car.model);
  120.  
  121. }
  122.  
  123. var Cadillac=makeCar();
  124.  
  125. displayCar(Cadillac);
  126.  
  127. //访问对象中的属性
  128.  
  129. //方法一:迭代器
  130.  
  131. for(var pup in Cadillac)
  132.  
  133. {
  134.  
  135. console.log(pup+" : "+ Cadillac[pup]);
  136.  
  137. }
  138.  
  139. //方法二:句点访问法和方括号访问法
  140.  
  141. console.log("You new car 's color is "+Cadillac.color);
  142.  
  143. console.log("Your car counld hold "+Cadillac["passengers"]+" people.");
  144.  
  145. console.log("Your car counld hold "+Cadillac["passe"+"ngers"]+" people.");
  146.  
  147. Cadillac.drive();//开车
  148.  
  149. Cadillac.start();//启动
  150.  
  151. Cadillac.drive();//开车
  152.  
  153. Cadillac.addFuel(15);//加油
  154.  
  155. Cadillac.start();//启动
  156.  
  157. Cadillac.drive();//开车
  158.  
  159. Cadillac.stop();//熄火
  160.  
  161. Cadillac.drive();//开车
  162.  
  163. </script>
  164.  
  165. </body>
  166. </html>
  167.  

4 对象拓展

  JavaScript提供:

  Date, Math, RegExp(字符串中查找), JSON(与其他应用程序交换js对象)

  浏览器提供:

  Doucument(写入网页),Windows(,与浏览器相关),Console(与控制台相关)

五、高级对象构造技巧

1 构造函数创建对象(模板)

  • 构造函数只能返回this;否则会导致函数不返回它创建的对象;
  • 判断某个实例是否由某个构造函数创建;
  • cadi instanceof Dog;是返回true;
  • 当然可以使用上面阐述的方式更改对象的属性和方法,更改后,intanceof依然显示true;
  1. <!doctype html>
  2.  
  3. <html lang="en">
  4.  
  5. <head>
  6.  
  7. <title>Dog wang!</title>
  8.  
  9. <meta charset="utf-8">
  10.  
  11. <style type="text/css">
  12.  
  13. </style>
  14.  
  15. <script language="JavaScript" type="text/JavaScript">
  16.  
  17. //构造函数
  18.  
  19. function Dog(name,breed,weight){
  20.  
  21. this.name=name;
  22.  
  23. this.breed=breed;
  24.  
  25. this.weight=weight;
  26.  
  27. this.bark=function(){
  28.  
  29. if(this.weight>25)
  30.  
  31. alert(this.name+" says Woof!");
  32.  
  33. else
  34.  
  35. alert(this.name+" says Yip!");
  36.  
  37. };
  38.  
  39. }
  40.  
  41. var fido = new Dog("Fido", "Mixed", 38);
  42.  
  43. var fluffy = new Dog("Fluffy", "Poodle", 30);
  44.  
  45. var spot = new Dog("Spot", "Chihuahua", 10);
  46.  
  47. var dogs = [fido, fluffy, spot];
  48.  
  49. for(var i = 0; i < dogs.length; i++) {
  50.  
  51. var size = "small";
  52.  
  53. if (dogs[i].weight > 10) {
  54.  
  55. size = "large";
  56.  
  57. }
  58.  
  59. console.log("Dog: " + dogs[i].name
  60.  
  61. + " is a " + size
  62.  
  63. + " " + dogs[i].breed
  64.  
  65. );
  66.  
  67. }
  68.  
  69. for (var i = 0; i < dogs.length; i++) {
  70.  
  71. dogs[i].bark();
  72.  
  73. }
  74.  
  75. </script>
  76.  
  77. </head>
  78.  
  79. <body>
  80.  
  81. </body>
  82.  
  83. </html>

2 内置构造函数

  1. var now=new Date();
  2.  
  3. var dateString=now.toString();
  4.  
  5. var year=now.getFullYear();
  6.  
  7. var birthday=new Date("May 1,1998 08:09 pm");
  8.  
  9. console.log(birthday.toString());
  10.  
  11. console.log(dateString);
  12.  
  13. console.log(year);

3 数组对象

var items=new Array("a","b","c");

console.log(items[2]);

4 其他内置对象

Object【对象字面量是其实例】,Math,RegExp,Error

5 使用原型创建对象

  • 在所使用上述构造函数创建对象时,每个不同的对象都需要分配内存(主要是行为),为了节约内存管理提出了继承原型的方式创建对象,实质也是继承对象;
  • Dog.prototype访问原型
  • 原理:所有方法和属性都是先在实例对象中查找调用,如果不存在则返回原型查找调用并将原型的属性方法添加给实例对象;
  • spot.hasOwnProperty("sitting")可以测试sitting属性是否在实例对象spot中存在,存在返回true否则false;
  • 学会创建原型链对象,最初始的都是Object对象
  • 例:
  1. <!doctype html>
  2.  
  3. <html lang="en">
  4.  
  5. <head>
  6.  
  7. <meta charset="utf-8">
  8.  
  9. <title>Show dogs</title>
  10.  
  11. <script>
  12.  
  13. //创建狗狗的原型
  14.  
  15. function Dog(name, breed, weight) {
  16.  
  17. this.name = name;
  18.  
  19. this.breed = breed;
  20.  
  21. this.weight = weight;
  22.  
  23. }
  24.  
  25. //为狗狗添加属性
  26.  
  27. Dog.prototype.species = "Canine";
  28.  
  29. Dog.prototype.sitting = false;
  30.  
  31. //为狗狗添加方法
  32.  
  33. Dog.prototype.sit = function() {
  34.  
  35. if (this.sitting) {
  36.  
  37. console.log(this.name + " is already sitting");
  38.  
  39. } else {
  40.  
  41. console.log(this.name + " is now sitting");
  42.  
  43. this.sitting = true;
  44.  
  45. }
  46.  
  47. }
  48.  
  49. Dog.prototype.bark = function() {
  50.  
  51. if (this.weight > 25) {
  52.  
  53. console.log(this.name + " says Woof!");
  54.  
  55. } else {
  56.  
  57. console.log(this.name + " says Yip!");
  58.  
  59. }
  60.  
  61. };
  62.  
  63. Dog.prototype.run = function() {
  64.  
  65. console.log("Run!");
  66.  
  67. };
  68.  
  69. Dog.prototype.wag = function() {
  70.  
  71. console.log("Wag!");
  72.  
  73. };
  74.  
  75. //创建一个表演狗的原型——构造函数
  76.  
  77. /*
  78.  
  79. function ShowDog(name, breed, weight, handler) {
  80.  
  81. this.name = name;
  82.  
  83. this.breed = breed;
  84.  
  85. this.weight = weight;
  86.  
  87. this.handler = handler;
  88.  
  89. }
  90.  
  91. */
  92.  
  93. //改进版
  94.  
  95. function ShowDog(name,breed,weight,handler)
  96.  
  97. {
  98.  
  99. Dog.call(this,name,breed,weight);//重用构造函数Dog中处理name等的代码
  100.  
  101. this.handler=handler;
  102.  
  103. }
  104.  
  105. //使表演狗原型继承自狗狗原型
  106.  
  107. ShowDog.prototype = new Dog();
  108.  
  109. //重写ShowDog的constructor属性
  110.  
  111. ShowDog.prototype.constructor=ShowDog;
  112.  
  113. //为表演狗原型添加新属性
  114.  
  115. ShowDog.prototype.league = "Webville";
  116.  
  117. //为表演狗原型添加方法
  118.  
  119. ShowDog.prototype.stack = function() {
  120.  
  121. console.log("Stack");
  122.  
  123. };
  124.  
  125. ShowDog.prototype.bait = function() {
  126.  
  127. console.log("Bait");
  128.  
  129. };
  130.  
  131. ShowDog.prototype.gait = function(kind) {
  132.  
  133. console.log(kind + "ing");
  134.  
  135. };
  136.  
  137. ShowDog.prototype.groom = function() {
  138.  
  139. console.log("Groom");
  140.  
  141. };
  142.  
  143. //创建狗狗原型的实例对象
  144.  
  145. var fido = new Dog("Fido", "Mixed", 38);
  146.  
  147. var fluffy = new Dog("Fluffy", "Poodle", 30);
  148.  
  149. var spot = new Dog("Spot", "Chihuahua", 10);
  150.  
  151. //重写spot实例的bark方法
  152.  
  153. spot.bark = function() {
  154.  
  155. console.log(this.name + " says WOOF!");
  156.  
  157. };
  158.  
  159. //创建表演狗原型的实例对象
  160.  
  161. var scotty = new ShowDog("Scotty", "Scottish Terrier", 15, "Cookie");
  162.  
  163. var beatrice = new ShowDog("Beatrice", "Pomeranian", 5, "Hamilton");
  164.  
  165. //测试狗狗原型实例对象的方法调用
  166.  
  167. fido.bark();
  168.  
  169. fluffy.bark();
  170.  
  171. spot.bark();
  172.  
  173. //测试表演狗原型实例对象的方法调用
  174.  
  175. scotty.bark();
  176.  
  177. beatrice.bark();
  178.  
  179. scotty.gait("Walk");
  180.  
  181. beatrice.groom();
  182.  
  183. //测试实例的constructor属性
  184.  
  185. console.log("FIdo constructor is "+fido.constructor);
  186.  
  187. console.log("Scotty constructor is "+scotty.constructor);
  188.  
  189. </script>
  190.  
  191. </head>
  192.  
  193. <body>
  194.  
  195. </body>
  196.  
  197. </html>
  • 重写内置行为

    • 如:重写Object的toString()方法
    • 不可重写属性:

constructor 指向与这个原型相关联的构造函数

hasOwnProperty判断实例中是否实例化

isPrototypeOf 判断一个对象是否是另一个对象的原型

propertyIsEnumerable 判断通过迭代对象的所有属性是否可访问指定属性

  • 可重写:

toString 转换为字符串

toLocaleString 将对象转换为字符串,通过重写可以描述对象的本地化字符串

valueOf 默认返回当前对象,通过重写让它返回你希望的其他值;

  1. <script>
  2.  
  3. function Robot(name,year,owner)
  4.  
  5. {
  6.  
  7. this.name=name;
  8.  
  9. this.year=year;
  10.  
  11. this.owner=owner;
  12.  
  13. }
  14.  
  15. var toy=new Robot("Toy",2013,"Avary");
  16.  
  17. console.log(toy.toString());
  18.  
  19. function Robot2(name,year,owner)
  20.  
  21. {
  22.  
  23. this.name=name;
  24.  
  25. this.year=year;
  26.  
  27. this.owner=owner;
  28.  
  29. }
  30.  
  31. //重写Object的toString方法
  32.  
  33. Robot2.prototype.toString=function(){
  34.  
  35. return this.name+" Robot2 beloneing to "+this.owner;
  36.  
  37. }
  38.  
  39. var toy2=new Robot2("Toy",2013,"Avary");
  40.  
  41. console.log(toy2.toString());
  42.  
  43. </script>
  • 拓展内置对象

给String等内置对象添加新方法时,务必确保新方法名称不与对象既有名称冲突,链接其他代码时一定要清楚这些代码包含的自定义拓展,有些内置对象如Array不能拓展

  1. <script>
  2.  
  3. //为String的原型添加方法cliche
  4.  
  5. String.prototype.cliche=function(){
  6.  
  7. var cliche=["lock and load","touch base","open the kimono"];
  8.  
  9. for(var i=0;i<cliche.length;i++){
  10.  
  11. var index=this.indexOf(cliche[i]);
  12.  
  13. if(index>=0){
  14.  
  15. return true;
  16.  
  17. }
  18.  
  19. }
  20.  
  21. return false;
  22.  
  23. }
  24.  
  25. var sentences=["I'll send my car around to pick you up",
  26.  
  27. "Let's touch base in the moring and see where we are",
  28.  
  29. "We don't want to open the kimono,we just want to inform them."];
  30.  
  31. for(var i=0;i<sentences.length;i++){
  32.  
  33. var parse=sentences[i];
  34.  
  35. if(parse.cliche){
  36.  
  37. console.log("CliCHE ALERT: "+parse);
  38.  
  39. }
  40.  
  41. }
  42.  
  43. </script>

JavaScript学习笔记(三)——对象的更多相关文章

  1. JavaScript:学习笔记(8)——对象扩展运算符

    JavaScript:学习笔记(8)——扩展运算符 对象的扩展运算符 扩展运算符是三个点(...).用于取出参数对象的所有可遍历属性,然后拷贝到当前对象之中. 如上图所示,新建了一个对象a,然后通过扩 ...

  2. Javascript学习笔记三——操作DOM(二)

    Javascript学习笔记 在我的上一个博客讲了对于DOM的基本操作内容,这篇继续巩固一下对于DOM的更新,插入和删除的操作. 对于HTML解析的DOM树来说,我们肯定会时不时对其进行一些更改,在原 ...

  3. JavaScript学习笔记——BOM_window对象

    javascript浏览器对象模型-windwo对象 BOM Browser Object Model window对象 是BOM中所有对象的核心. 一.属性 1.(位置类型-获得浏览器的位置) IE ...

  4. JavaScript学习笔记之对象

    目录 1.自定义对象 2.Array 3.Boolean 4.Date 5.Math 6.Number 7.String 8.RegExp 9.Function 10.Event 在 JavaScri ...

  5. JavaScript学习笔记(三)——this、原型、javascript面向对象

    一.this 在JavaScript中this表示:谁调用它,this就是谁. JavaScript是由对象组成的,一切皆为对象,万物皆为对象.this是一个动态的对象,根据调用的对象不同而发生变化, ...

  6. JS学习笔记 (三) 对象进阶

    1.JS对象 1.1 JS对象特征 1.JS对象是基本数据数据类型之一,是一种复合值,可以看成若干属性的集合. 属性是名值对的形式(key:value) 属性名是字符串,因此可以把对象看成是字符串到值 ...

  7. JavaScript学习笔记-JSON对象

    JSON 是一种用来序列化对象.数组.数值.字符串.布尔值和 null 的语法.它基于 JavaScript 语法,但是又有区别:一些 JavaScript 值不是 JSON,而某些 JSON 不是 ...

  8. JavaScript学习笔记——DOM_document对象

    javascript-document对象详解 DOM document(html xml) object modledocument对象(DOM核心对象) 作用: 1.内容 innerHTML 2. ...

  9. JavaScript学习笔记(三十八) 复制属性继承

    复制属性继承(Inheritance by Copying Properties) 让我们看一下另一个继承模式—复制属性继承(inheritance by copying properties).在这 ...

  10. JavaScript学习笔记——3.对象

    JavaScript 对象 - 创建对象 1- var obj = new Object(); 2- var obj = {}; *例子:var person = {Name:"Hack&q ...

随机推荐

  1. linux文件系统写过程简析

    linux写入磁盘过程经历VFS ->  页缓存(page cache) -> 具体的文件系统(ext2/3/4.XFS.ReiserFS等) -> Block IO ->设备 ...

  2. Redhat7.2 ----team网卡绑定

    我先声明一下,team和bonding是一样的作用,只不过team多了几项功能bonding没有, 做team我们要最少准备两个网卡,我们这里主要显示主备模式. 首先我们先把网卡配置文件删除 nmcl ...

  3. Java Activiti 流程审批 后台框架源码 springmvc SSM 工作流引擎

    即时通讯:支持好友,群组,发图片.文件,消息声音提醒,离线消息,保留聊天记录 工作流模块-------------------------------------------------------- ...

  4. Tarjan算法初探(2):缩点

    接上一节 Tarjan算法初探(1):Tarjan如何求有向图的强连通分量 Tarjan算法一个非常重要的应用就是 在一张题目性质在点上性质能够合并的普通有向图中将整个强连通分量视作一个点来把整张图变 ...

  5. Linux下onvif客户端获取ipc摄像头 GetProfiles:获取h265媒体信息文件

    GetProfiles:获取媒体信息文件 鉴权:但是在使用这个接口之前是需要鉴权的.ONVIF协议规定,部分接口需要鉴权,部分接口不需要鉴权,在调用需要鉴权的接口时不使用鉴权,会导致接口调用失败.实现 ...

  6. MySQL----MySQL数据库入门----第二章 数据库和表的基本操作

    2.1 数据库和数据库表的创建 ①数据库的创建(在数据库系统中划分一块存储数据的空间): create database 数据库名称 [charset 字符集]: ②数据库表的创建 use 数据库名 ...

  7. td内的所有数字格式化保留两位小数

    $("td").each(function(i,el){ var td = parseFloat($(el).text()); if(!isNaN(td)){ $(el).text ...

  8. es6之扩展运算符 三个点(...)

    对象的扩展运算符理解对象的扩展运算符其实很简单,只要记住一句话就可以: 对象中的扩展运算符(...)用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中 let bar = { a: 1, b: 2 ...

  9. php添加数据库转义特殊字符串

    addslashes()

  10. PHP打包zip并下载

    $file_template = FCPATH.'canddata/cand_picture.zip';//在此之前你的项目目录中必须新建一个空的zip包(必须存在) $downname = $car ...