js继承
2016-01-20 17:16
691 查看
var o = { a: 2, m: function(){ return this.a + 1; } }; console.log(o.m()); // 3 // 当调用 o.m 时,'this'指向了o. var p = Object.create(o); // p是一个对象, p.[[Prototype]]是o. p.a = 12; // 创建 p 的自身属性a. console.log(p.m()); // 13 // 调用即 p.a,即 p 的自身属性 'a'[/code]p.m时, 'this'指向 p.
// 又因为 p 继承 o 的 m 函数
// 此时的[code]'this.a'
function A(a){ this.varA = a; } // 以上函数 A 的定义中,既然 A.prototype.varA 总是会被 this.varA 遮蔽, // 那么将 varA 加入到原型(prototype)中的目的是什么? A.prototype = { varA : null, // 既然它没有任何作用,干嘛不将 varA 从原型(prototype)去掉? //也许作为一种在隐藏类中优化分配空间的考虑?
// https://developers.google.com/speed/articles/optimizing-javascript#Initializing instance variables // 将会验证如果 varA 在每个实例不被特别初始化会是什么情况。 doSomething : function(){ // ... } } function B(a, b){ A.call(this, a); this.varB = b; } B.prototype = Object.create(A.prototype, { varB : { value: null, enumerable: true, configurable: true, writable: true }, doSomething : { value: function(){ // override A.prototype.doSomething.apply(this, arguments); // call super // ... }, enumerable: true, configurable: true, writable: true } }); B.prototype.constructor = B; var b = new B(); b.doSomething();最重要的部分是:类型被定义在
.prototype 中
而你用
Object.create()来继承
相关文章推荐
- js创建jsonArray
- Javascript中神奇的this
- json to js OR js to json
- js006-面向对象的程序设计
- js删除数组里的某个元素
- js 数组排序
- JS encodeURI和encodeURIComponent
- js利用clipboardData在网页中实现截屏粘贴的功能
- angular js表单验证
- list数组转换为json数组
- JSON
- js 时间格式化 -- 时间加减实现
- javascript实现图片轮播效果
- jsp页面显示多张FTP上图片
- json_decode和json_encode
- JSON格式化
- jsp页面显示多张FTP服务器图片的方法
- 用JS获取地址栏参数的方法(超级简单)
- js取小数点两位
- js 打印指定页面部分打印