zoukankan      html  css  js  c++  java
  • JavaScript学习笔记(三)——对象

    第四章 理解对象

    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  
     32 
     33 var rand1=Math.floor(Math.random()*makes.length);
     34 
     35 var rand2=Math.floor(Math.random()*models.length);
     36 
     37 var rand3=Math.floor(Math.random()*years.length);
     38 
     39 var rand4=Math.floor(Math.random()*colors.length);
     40 
     41 var rand5=Math.floor(Math.random()*5)+1;
     42 
     43 var rand6=Math.floor(Math.random()*2);
     44 
     45  
     46 
     47 var car={
     48 
     49 make:makes[rand1],
     50 
     51 model:models[rand2],
     52 
     53 year:years[rand3],
     54 
     55 color:colors[rand4],
     56 
     57 passengers:rand5,
     58 
     59 convertile:convertile[rand6],
     60 
     61 mileage:0,
     62 
     63 fuel:0,
     64 
     65 started:false,
     66 
     67  
     68 
     69 start:function(){
     70 
     71 this.started=true;
     72 
     73 },
     74 
     75 stop:function(){
     76 
     77 this.started=false;
     78 
     79 },
     80 
     81 drive:function(){
     82 
     83 if(this.started)
     84 
     85 {
     86 
     87 if(this.fuel>0)
     88 
     89 alert("Zoom zoom!");
     90 
     91 else
     92 
     93 {
     94 
     95 alert("Uh , oh ,out of fuel!");
     96 
     97 this.stop();
     98 
     99 }
    100 
    101 }
    102 
    103 else
    104 
    105 alert("You need to start the engine first!");
    106 
    107 },
    108 
    109 addFuel:function(amount){
    110 
    111 this.fuel+=amount;
    112 
    113 }
    114 
    115 };
    116 
    117 return car;
    118 
    119 }
    120 
    121 function displayCar(car)
    122 
    123 {
    124 
    125 console.log("Your new car is a "+car.year+" "+car.make+" "+car.model);
    126 
    127 }        
    128 
    129 var Cadillac=makeCar();
    130 
    131 displayCar(Cadillac);
    132 
    133 //访问对象中的属性
    134 
    135 //方法一:迭代器
    136 
    137 for(var pup in Cadillac)
    138 
    139 {
    140 
    141 console.log(pup+" : "+        Cadillac[pup]);
    142 
    143 }
    144 
    145 //方法二:句点访问法和方括号访问法
    146 
    147 console.log("You new car 's color is "+Cadillac.color);
    148 
    149 console.log("Your car counld hold "+Cadillac["passengers"]+" people.");
    150 
    151 console.log("Your car counld hold "+Cadillac["passe"+"ngers"]+" people.");
    152 
    153  
    154 
    155 Cadillac.drive();//开车
    156 
    157 Cadillac.start();//启动
    158 
    159 Cadillac.drive();//开车
    160 
    161 Cadillac.addFuel(15);//加油
    162 
    163 Cadillac.start();//启动
    164 
    165 Cadillac.drive();//开车
    166 
    167 Cadillac.stop();//熄火
    168 
    169 Cadillac.drive();//开车
    170 
    171 </script>
    172 
    173 </body>
    174 </html>


    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  
    14 
    15 </style>
    16 
    17 <script language="JavaScript" type="text/JavaScript">
    18 
    19 //构造函数
    20 
    21 function Dog(name,breed,weight){
    22 
    23 this.name=name;
    24 
    25 this.breed=breed;
    26 
    27 this.weight=weight;
    28 
    29 this.bark=function(){
    30 
    31 if(this.weight>25)
    32 
    33 alert(this.name+" says Woof!");
    34 
    35 else
    36 
    37 alert(this.name+" says Yip!");
    38 
    39 };
    40 
    41 }
    42 
    43  
    44 
    45 var fido = new Dog("Fido", "Mixed", 38);
    46 
    47 var fluffy = new Dog("Fluffy", "Poodle", 30);
    48 
    49 var spot = new Dog("Spot", "Chihuahua", 10);
    50 
    51 var dogs = [fido, fluffy, spot];
    52 
    53  
    54 
    55 for(var i = 0; i < dogs.length; i++) {
    56 
    57 var size = "small";
    58 
    59 if (dogs[i].weight > 10) {
    60 
    61 size = "large";
    62 
    63 }
    64 
    65 console.log("Dog: " + dogs[i].name
    66 
    67 + " is a " + size
    68 
    69 + " " + dogs[i].breed
    70 
    71 );
    72 
    73 }
    74 
    75  
    76 
    77 for (var i = 0; i < dogs.length; i++) {
    78 
    79 dogs[i].bark();
    80 
    81 }
    82 
    83 </script>
    84 
    85 </head>
    86 
    87 <body>
    88 
    89  
    90 
    91 </body>
    92 
    93 </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  
    126 
    127 ShowDog.prototype.bait = function() {
    128 
    129 console.log("Bait");
    130 
    131 };
    132 
    133  
    134 
    135 ShowDog.prototype.gait = function(kind) {
    136 
    137 console.log(kind + "ing");
    138 
    139 };
    140 
    141  
    142 
    143 ShowDog.prototype.groom = function() {
    144 
    145 console.log("Groom");
    146 
    147 };
    148 
    149  
    150 
    151 //创建狗狗原型的实例对象
    152 
    153 var fido = new Dog("Fido", "Mixed", 38);
    154 
    155 var fluffy = new Dog("Fluffy", "Poodle", 30);
    156 
    157 var spot = new Dog("Spot", "Chihuahua", 10);
    158 
    159 //重写spot实例的bark方法
    160 
    161 spot.bark = function() {
    162 
    163 console.log(this.name + " says WOOF!");
    164 
    165 };
    166 
    167 //创建表演狗原型的实例对象
    168 
    169 var scotty = new ShowDog("Scotty", "Scottish Terrier", 15, "Cookie");
    170 
    171 var beatrice = new ShowDog("Beatrice", "Pomeranian", 5, "Hamilton");
    172 
    173 //测试狗狗原型实例对象的方法调用
    174 
    175 fido.bark();
    176 
    177 fluffy.bark();
    178 
    179 spot.bark();
    180 
    181 //测试表演狗原型实例对象的方法调用
    182 
    183 scotty.bark();
    184 
    185 beatrice.bark();
    186 
    187  
    188 
    189 scotty.gait("Walk");
    190 
    191 beatrice.groom();
    192 
    193 //测试实例的constructor属性
    194 
    195 console.log("FIdo constructor is "+fido.constructor);
    196 
    197 console.log("Scotty constructor is "+scotty.constructor);
    198 
    199 </script>
    200 
    201 </head>
    202 
    203 <body>
    204 
    205 </body>
    206 
    207 </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  
    20 
    21 function Robot2(name,year,owner)
    22 
    23 {
    24 
    25 this.name=name;
    26 
    27 this.year=year;
    28 
    29 this.owner=owner;
    30 
    31 }
    32 
    33 //重写Object的toString方法
    34 
    35 Robot2.prototype.toString=function(){
    36 
    37 return this.name+" Robot2 beloneing to "+this.owner;
    38 
    39 }
    40 
    41 var toy2=new Robot2("Toy",2013,"Avary");
    42 
    43 console.log(toy2.toString());
    44 
    45 </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  
    10 
    11 for(var i=0;i<cliche.length;i++){
    12 
    13 var index=this.indexOf(cliche[i]);
    14 
    15 if(index>=0){
    16 
    17 return true;
    18 
    19 }
    20 
    21 }
    22 
    23 return false;
    24 
    25 }
    26 
    27  
    28 
    29 var sentences=["I'll send my car around to pick you up",
    30 
    31 "Let's touch base in the moring and see where we are",
    32 
    33 "We don't want to open the kimono,we just want to inform them."];
    34 
    35 for(var i=0;i<sentences.length;i++){
    36 
    37 var parse=sentences[i];
    38 
    39 if(parse.cliche){
    40 
    41 console.log("CliCHE ALERT: "+parse);
    42 
    43 }
    44 
    45 }
    46 
    47 </script>
  • 相关阅读:
    android 中ImageButton按下改变背景图片的效果
    Android根据Button状态(normal,focused,pressed)显示不同背景图片
    Android简单逐帧动画Frame的实现(三)
    Android消息总线的演进之路:用LiveDataBus替代RxBus、EventBus
    美团点评云真机平台实践
    美团客户端响应式框架EasyReact开源啦
    MCI:移动持续集成在大众点评的实践
    如何基于深度学习实现图像的智能审核?
    Android自动化页面测速在美团的实践
    美团外卖iOS多端复用的推动、支撑与思考
  • 原文地址:https://www.cnblogs.com/weimingai/p/10349205.html
Copyright © 2011-2022 走看看