javascript对象中的constructor,prototype和__proto__
文章转自:http://www.cnblogs.com/winderby/articles/4039816.html
1.constructor
constructor是构造函数的原型的一个属性,他指向这个对象的构造函数。
function Tree(name) { this.name = name; } var theTree = new Tree('Redwood'); console.log(Tree.prototype.constructor);// function Tree(name){this.name = name} console.log(Tree.prototype.constructor === Tree);//true}
当创建一个构造函数时,他的原型自动创建constructor属性,结构如
Tree.prototype = { constructor: Tree .... }
实例化对象访问constructor实际访问的是构造函数的原型,
function Tree(name) { this.name = name; } var theTree = new Tree('Redwood'); console.log( theTree.hasOwnProperty('constructor') ) // false console.log( Tree.prototype.hasOwnProperty('constructor') ) // true
2.prototype
每一个构造函数都有一个属性叫做原型(prototype),如。
function Tree(name) { this.name = name; } console.log(Tree.prototype); //Object { ... }
他的重要意义是,每一个通过构造函数实例化的对象都可以访问构造函数的原型
function Tree(name) { this.name = name; } Tree.prototype.show = function(){ alert(this.name) } var theTree = new Tree("Redwood") var theTree2 = new Tree("Blackwood") theTree.show(); //Redwood theTree2.show(); //Blackwood
3.__ptroto__
__proto__是实例化的对象的一个属性,它指向构造函数的原型,如
function Tree(name) { this.name = name; } var theTree = new Tree("Redwood") console.log(theTree.__proto__ === Tree.prototype)//true
当我们改变实例化对象的__proto__,指向另一个对象,这个实例化可以访问其所有属性,但其属性不是实例化对象所有,Zepto框架就是这个原理。
function Tree(name) { this.name = name; } var theTree = new Tree("Redwood") console.log(theTree.hasProperty("show"))//false theTree.__proto__ = { show: function(){ alert(this.name) } } theTree.show()//Redwood
4.javascript对象中的constructor,prototype和__proto__
这里来详细分析一个经典的例子,可以很好地理解对象的结构
// 构造函数 function Foo(y) { // this 指向实例化对象 // 添加对象的属性"y" this.y = y; } // 可以通过语句向Foo.prototype对象中添加属性 // 当实例化时,实例化对象会继承这个属性 Foo.prototype.x = 10; // 添加函数属性 Foo.prototype.calculate = function (z) { return this.x + this.y + z; }; // 用Foo实例化两个对象 var b = new Foo(20); var c = new Foo(30); // 调用继承的函数属性 b.calculate(30); // 60 c.calculate(40); // 80 // 仔细分析相关属性 console.log( b.__proto__ === Foo.prototype, // true c.__proto__ === Foo.prototype, // true // "Foo.prototype"自动创建一个属性 // "constructor",指向构造函数 // 实例化对象可以通过访问构造函数的原型来访问它 b.constructor === Foo, // true c.constructor === Foo, // true Foo.prototype.constructor === Foo, // true b.calculate === b.__proto__.calculate, // true b.__proto__.calculate === Foo.prototype.calculate // true );
上述代码对象的结构图,如下: