< 3; i++) { (data[i] = function () { console.log(arguments.callee.i)}).i = i;}data[0]();data[1]();data[2]();// 0// 1// 2非严格模式下,实参和argument的值会共享(绑定)严格模式下,实参和argument的值不会共享
继承的多种方式以及优缺点原型链继承Function Perent(){this.name = 'kevin'}Perent.prototype.getName() = function(){Console.log(this.name)}function Child () {}Child.prototype = new Parent();var child1 = new Child();console.log(child1.getName()) // kevin
引用类型的属性会被所有实例共享,并且不能向Perent传参
构造函数继承function Parent () { this.names = ['kevin', 'daisy'];}function Child () { Parent.call(this);}var child1 = new Child();child1.names.push('yayu');console.log(child1.names); // ["kevin", "daisy", "yayu"]var child2 = new Child();console.log(child2.names); // ["kevin", "daisy"]
解决了利用原型链继承的问题缺点:方法在构造函数中定义,每次创建实例都会创建一遍方法
组合继承构造函数继承+原型链继承结合了两者的优点,是常见的继承方式
原型式继承function createObj(o) { function F(){} F.prototype = o; return new F();}
同样存在共享的问题,但是在给对象赋值时会优先添加值
寄生式继承创建一个仅用于封装过程的函数
function createObj (o) { var clone = Object.create(o); clone.sayName = function () { console.log('hi'); } return clone;}
寄生组合式继承function Parent (name) { this.name = name; this.colors = ['red', 'blue', 'green'];}Parent.prototype.getName = function () { console.log(this.name)}function Child (name, age) { Parent.call(this, name); this.age = age;}Child.prototype = new Parent();var child1 = new Child('kevin', '18');console.log(child1)
可以发现其调用了两次父构造函数,一次是new perent,一次是new child为了避免重复的调用,可以这样做
var F = function () {};F.prototype = Parent.prototype;Child.prototype = new F();var child1 = new Child('kevin', '18');console.log(child1);
设置一个空对象作为跳板,即可减少父构造函数的调用封装过后就是
function object(o) { function F() {} F.prototype = o; return new F();}function prototype(child, parent) { var prototype = object(parent.prototype); prototype.constructor = child; child.prototype = prototype;}
当要使用的时候,就prototype(Child, Parent);开发人员普遍认为寄生组合式继承是引用类型比较理想的继承范式
【Learning Records JavaScript进阶】
经验总结扩展阅读
- javascript编程单线程之异步模式Asynchronous
- javascript编程单线程之同步模式
- JavaScript函数式编程之函子
- GGD 论文解读《Rethinking and Scaling Up Graph Contrastive Learning: An Extremely Efficient Approach with Group Discrimination》
- 原生JavaScript
- Learning Records 计算机网络
- JavaScript之无题之让人烦躁的模块化
- GACL 谣言检测《Rumor Detection on Social Media with Graph Adversarial Contrastive Learning》
- Javascript 手写 LRU 算法