原型
1、所有的函数都天生自带一个属性:prototype(原型),他是一个对象数据类型的值,在当前prototype对象中,存储了类需要给其他实例的公有的属性和方法
2、prototype这个对象,浏览器会默认为其开辟一个堆内存,在堆内存中天生自带一个属性:constructor(构造函数),这个属性值是当前函数本身
3、每一个类的实例(每一个对象)都天生自带一个属性:_proto_,属性值是当前对象所属类的原型(prototype)
function Fn(name, age) {
this.name = name;
this.age = age;
this.say = function() {
console.log(this.name, this.age)
}
}
Fn.prototype.saytwo = function(){
console.log('hello world')
}
var f = new Fn('ggr', 18)
批量设置原型(重新构造原型)
function Fn(name, age) {
this.name = name;
this.age = age;
this.say = function() {
console.log(this.name, this.age)
}
}
Fn.prototype = {
// 让原型指向自己开辟的堆内存
// 让构造函数指向Fn函数本身
constructor: Fn,
aa:function() {
},
bb:function() {
}
}
var f = new Fn('ggr', 18)
深入理解arguments
function Fn(){
console.log(arguments)
}
var f1 = new Fn(1,2,3,4,5)
通过图片可以看到arguments的_proto指向Object原型,所以不具备Array的属性方法,可以通过
arguments.\__proto__ == Array.prototype
来实现可以使用数组方法,但是需要注意ie浏览器下禁止修改_proto所以可以用于移动端
利用call实现arguments可以使用数组类的方法
function fn(){
var arg = [].slice.call(arguments)
console.log(arg)
};
fn(1,2,3,3,4,5)
类数组转数组兼容处理
var utils = (function() {
function toArray(arr) {
var ary = [];
try {
ary = Array.prototype.call(arr)
} catch (e) {
for (var i = 0; i < arr.length; i++) {
ary[ary.length] = arr[i]
}
}
return ary
}
return {
toArray: toArray,
}
})();