为了让属性和方法更好的体现封装的效果,并且减少不必要的输入,原型的创建可以使用字面量的方式:
使用构造函数创建原型对象和使用字面量创建对象在使用上基本相同,但还是有一些区别,字面量创建的方式使用 constructor 属性不会指向实例,而会指向 Object,构造函数创建的方式则相反。
<head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>基本包装类型</title> <script type="text/javascript"> function Box() {}; Box.prototype = { //使用字面量的方式创建原型对象,这里{}就是对象,是Object,new Object就相当于{} name : ‘Lee‘, age : 100, run : function () { return this.name + this.age + ‘运行中...‘; } }; var box = new Box(); alert(box instanceof Box); alert(box instanceof Object); alert(box.constructor == Box); //字面量方式,返回 false,否则,true alert(box.constructor == Object); //字面量方式,返回 true,否则,false </script> </head>
如果想让字面量方式的 constructor 指向实例对象,那么可以这么做:定义的时候加上constructor : Box,
<head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>基本包装类型</title> <script type="text/javascript"> function Box() {}; Box.prototype = { //使用字面量的方式创建原型对象,这里{}就是对象,是Object,new Object就相当于{} constructor : Box, //直接强制指向即可 name : ‘Lee‘, age : 100, run : function () { return this.name + this.age + ‘运行中...‘; } }; var box = new Box(); alert(box.age); alert(box instanceof Box); alert(box instanceof Object); alert(box.constructor == Box); //true alert(box.constructor == Object); //false </script> </head>
PS:字面量方式为什么 constructor 会指向 Object?因为
Box.prototype={};这种写法其实就是创建了一个新对象。而每创建一个函数,就会同时创建它 prototype,这个对象也会自动获取
constructor 属性。所以,新对象的 constructor 重写了 Box 原来的
constructor,因此会指向新对象,那个新对象没有指定构造函数,那么就默认为 Object。
原型的声明是有先后顺序的,所以,重写的原型会切断之前的原型。
<head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>基本包装类型</title> <script type="text/javascript"> function Box() {}; Box.prototype = { //使用字面量的方式创建原型对象,这里{}就是对象,是Object,new Object就相当于{} constructor : Box, //直接强制指向即可 name : ‘Lee‘, age : 100, run : function () { return this.name + this.age + ‘运行中...‘; } }; //重写原型对象 Box.prototype = { name : ‘cary‘, //这里不会保留之前原型的任何信息了,把原来的原型对象和构造函数对象实例之间的关系切断了 } var box = new Box(); alert(box.age); </script> </head>
原型对象不仅仅可以在自定义对象的情况下使用,而 ECMAScript 内置的引用类型都可以使用这种方式,并且内置的引用类型本身也使用了原型。
<head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>基本包装类型</title> <script type="text/javascript"> alert(Array.prototype.sort); //sort 就是 Array 类型的原型方法 alert(String.prototype.substring); //substring 就是 String 类型的原型方法 String.prototype.addstring = function () { //给 String 类型添加一个方法 return this + ‘,被添加了!‘; //this 代表调用的字符串 }; alert(‘Lee‘.addstring()); //使用这个方法 </script> </head>
尽管给原生的内置引用类型添加方法使用起来特别方便,但我们不推荐使用这种方法。因为它可能会导致命名冲突,不利于代码维护。
原文:http://www.cnblogs.com/LO-ME/p/3601306.html