Learning Records JavaScript进阶( 四 )


bindbind会创建一个新函数,bind的第一个参数会作为它运行时的this
var foo = { value: 1};function bar() { console.log(this.value);}// 返回了一个函数var bindFoo = bar.bind(foo); bindFoo(); // 1类数组对象和arguments类数组对象指拥有一个length属性和若干索引属性的对象如
var array = ['name', 'age', 'sex'];var arrayLike = { 0: 'name', 1: 'age', 2: 'sex', length: 3}可以发现类数组对象和数组的长度,遍历,读写一样但是类数组对象是不能用数组的方法的但是类数组可以通过各种方法转化成数组
argumentsfunction foo(name, age, sex) { console.log(arguments);}foo('name', 'age', 'sex')

Learning Records JavaScript进阶

文章插图
在之前的介绍中我们其实已经对argument有了一定的了解
lengtharguments的length表示实参的个数它所对应函数的length表示形参的个数
callee通过该属性函数可以调用自身
var data = https://www.huyubaike.com/biancheng/[];for (var i = 0; i < 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);开发人员普遍认为寄生组合式继承是引用类型比较理想的继承范式

推荐阅读