- var me = {
- name: 'pengxiaohua',
- age: 26,
- height: '184cm'
- }
- var me = new Object();
- me.name = "pengxiaohua";
- me.age = 26;
- me.height = "184cm";
- var Me = function() {
- this.name = 'pengxiaohua',
- this.age = 26,
- this.height = '184cm'
- }
- var me = new Me();
- var Me = {
- name: 'pengxiaohua',
- age: 26,
- height: '184cm',
- }
- var me = Object.create(Me);
- me // {}
- me.__proto__
- // {name: "pengxiaohua", age: 26, height: "184cm"}
Object.create 方法是把原对象 Me 的原型对象赋给新对象 me 的,所以此时调用 me 的__proto__方法可以成功创建对象。
原型链:每一个对象都有自己的原型对象,原型对象本身也是对象,原型对象也有自己的原型对象,这样就形成了一个链式结构,叫做原型链。
原型、构造函数和实例
上面的代码示例中创造原型对象方法中:
- var Me = function() {
- this.name = 'pengxiaohua',
- this.age = 26,
- this.height = '184cm'
- }
- // 通过new方法创建一个构造函数的实例对象
- var me = new Me();
- // 构造函数原型对象的constructor等于它自身
- Me.prototype.constructor === Me // true
- // 实例对象的__proto__等于构造函数的原型对象
- me.__proto__ === Me.prototype // true
- // 通过原型链的方式,找到原型对象,原型对象上的方法是被不同的实例对象所共有的,这就是原型链的工作原理
- Me.prototype.weight = '75kg';
- me.weight // "75kg"
几点注意:
① 只有函数有 prototype
② 只有实例对象才有__proto__
③ 函数也有__proto__,本质上函数也是对象,因为函数是 Function 的一个实例,同时也可以理解为,任何一个函数都是构造函数 Function 的实例。
- var obj = {a:1};
- var add = function(a, b) {
- return a+b;
- }
- obj.__proto__ === Object.prototype
- add.__proto__ === Function.prototype
instanceof
instanceof 的原理就是来判断,实例对象的__proto__属性和构造函数的 prototype 属性是不是引用同一个地址,如果是,则 instanceof 返回 true,否则返回 false。
- var Me = function() {
- this.name = 'pengxiaohua',
- this.age = 26,
- this.height = '184cm'
- }
- var me = new Me();
- me // Me {name: "pengxiaohua", age: 26, height: "184cm"}
- me instanceof Me // true
- me instanceof Object // true
- me.__proto__ === Me.prototype // true
- // Me.prototype也是一个实例对象,它的`__proto__`属性指向的是Object.prototype,如下,Me原型对象的`__proto__`指向的事Object的原型对象,所以Object也会被instanceof看作是me的构造函数。
- Me.prototype.__proto__ === Object.prototype // true
但是这种判断
是否真的准确呢?
- me instanceof Object
- var Me = function() {
- this.name = 'pengxiaohua',
- this.age = 26,
- this.height = '184cm'
- }
- var me = new Me();
- me.__proto__.constructor === Me; // true
- me.__proto__.constructor === Object // false
所以用 constructor 比用 instanceof 更加严谨。
来源: http://www.jianshu.com/p/776eb1aeaa90