理解JavaScript原型(3)
来源:未知 责任编辑:责任编辑 发表时间:2014-03-23 22:28 点击:次
//为函数b的原型属性添加一个属性max
b.prototype.max = 3
//实例c也有了一个属性max
c.max //3
上面的例子中,对象实例c的原型和函数的b的原型属性是一样的,如果改变b的原型属性,则对象实例c
的原型也会改变
———————————————————————————————————-
理解一个函数的原型属性(function’s prototype property )其实和实际的原型(prototype)没有关系对我们来说至关重要
//(example fails in IE)
var A = function (name) {
this .name = name;
}
A.prototype == A.__proto__; //false
A.__proto__ == Function.prototype; //true - A's prototype is set to its constructor's prototype property
给个例子撒
你可能曾经上百次的像这样使用javascript,现在当你再次看到这样的代码的时候,你或许会有不同的理解。
//Constructor. <em>this</em> is returned as new object and its internal [[prototype]] property will be set to the constructor's default prototype property
var Circle = function (radius) {
this .radius = radius;
//next line is implicit, added for illustration only
//this.__proto__ = Circle.prototype;
}
//augment Circle's default prototype property thereby augmenting the prototype of each generated instance
Circle.prototype.area = function () {
return Math.PI* this .radius* this .radius;
}
//create two instances of a circle and make each leverage the common prototype
var a = new Circle(3), b = new Circle(4);
a.area().toFixed(2); //28.27
b.area().toFixed(2); //50.27
棒极了。如果我更改了构造函数的原型,是否意味着已经存在的该构造函数的实例将获得构造函数的最新版本?
不一定。如果修改的是原型属性,那么这样的改变将会发生。因为在a实际被创建之后,a.__proto__是一个对A.prototype 的一个引用,。
var A = function (name) {
this .name = name;
}
var a = new A( 'alpha' );
a.name; //'alpha'
A.prototype.x = 23;
a.x; //23
——————————————————————————————————
译者注:这个和上例中的一样,实例对象a的原型(a.__proto__)是对函数A的原型属性(A.prototype)的引用,所以如果修改的是A的原型属性,
改变将影响由A创建的对象实例a 在下面的例子中,但是对函数A的原型进行了修改,但是并没有反应到A所创建的实例a中
相关新闻>>
- Javascript 兼容 IE6、IE7、FF 的“加入收藏”“设为首页”
- 好好学一遍JavaScript 笔记(一)——基础中的基础
- 好好学一遍JavaScript 笔记(二)——encode、数组、对象创建
- 好好学一遍JavaScript 笔记(三)——StringBuffer、prototype
- 好好学一遍javaScript 笔记(四)——Attribute、HTML元素、文档碎
- 好好学一遍JavaScript 笔记(五)——正则表达式基础
- 好好学一遍JavaScript 笔记(六)——正则表达式基础二
- 好好学一遍JavaScript 笔记(七)——RegExp对象与常用正则
- 好好学一遍JavaScript 笔记(八)——冒泡型事件、捕获型事件
- JavaScript详解
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>