对象的世界以及instanceof操作符
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script> 7 var Item = { 8 construct:function(name){ 9 this.name = name; 10 }, 11 inspect:function(){ 12 print("it is",this.name,"."); 13 14 }, 15 kick:function(){ 16 print("klunk!"); 17 }, 18 take:function(){ 19 print("you cannot lift",this.name,"."); 20 } 21 22 }; 23 var lantern = Item.create("the brass lantern"); 24 lantern.kick(); 25 //extend方法克隆调用它的对象,然后将参数里传入的属性添加到克隆的对象上 26 var DetailedItem = Item.extend({ 27 construct:function(name,details) { 28 Item.construct.call(this,name); 29 this.details=details; 30 }, 31 inspect:function(){ 32 print("you see",this.name,",".this.details,"."); 33 } 34 }); 35 var giantSloth = DetailedItem.create("the giant sloth","it is quietly hanging from a tree,muching leaves"); 36 giantSloth.inspect(); 37 38 var SmallItem = Item.extend({ 39 kick: function () { 40 print(this.name,"flies across the room."); 41 }, 42 take:function(){ 43 print("you take",this.name,"."); 44 } 45 }); 46 var pencil = SmallItem.create("the red pencil"); 47 pencil.take(); 48 49 object.prototype.isA=function(prototype){ 50 function DummyConstructor(){} 51 DummyConstructor.prototype = prototype; 52 return this instanceof DummyConstructor; 53 //instanceof操作符可用于确定一个对象是否基于指定的原型。 54 }; 55 pencil.isA(Item); 56 pencil.isA(DetailedItem); 57 58 59 </script> 60 </head> 61 <body> 62 63 </body> 64 </html>
欢迎关注微信公众号:“花栗鼠的红松树”
知乎专栏:“花栗鼠的红松树”
知乎: 卓怡 https://www.zhihu.com/people/zhuoyisun/activities
浙公网安备 33010602011771号