JavaScript的构造函数和原型链
目录
构造函数
var Vehicle = function () {
'use strict';
this.price = 1000;
};
- 是函数
- 首字母通常大写
- 使用了this,代表对象实例
- 生成对象使用new
new
- 创建空对象
- 将空对象的原型指向构造函数的prototype属性
- 将空对象赋值给函数内部的this关键字
- 执行构造函数内部的代码
Object.create()
var person1 = {
name: "张三",
age: 38,
greeting: function () {
console.log('Hi! I\'m ' + this.name + '.');
}
};
var person2 = Object.create(person1)
person2.name // 张三
person2.greeting() // Hi! I'm张三.
以现有对象为模板,生成新的实例对象,后者继承了前者的属性和方法
绑定this的方法
Function.prototype.call()
f.call(obj, arg1, arg2, …)
[1, 2, 3].slice(0, 1)
Array.prototype.slice.call([1, 2, 3], 0, 1)
Function.prototype.apply()
f.apply(obj, [arg1, arg2, …])
Math.max.apply(null, a)
Function.prototype.bind()
var counter = {
count: 0,
inc: function () {
this.count++;
}
};
var func = counter.inc.bind(counter);
func();
counter.count // 1
通过“原型对象”实现继承
原型对象的所有属性和方法,都能被实例对象共享
每个函数都有一个prototype属性,指向一个对象,对构造函数来说,该属性会自动成为实例对象的原型。
所有的对象都有自己的原型对象(prototype),所有对象的原型最终都可以上溯到Object.prototype,即Object构造函数的prototype属性。原型链的尽头是null。
valueOf、toString
f.constructor对象的构造函数
Person.prototype.constructor === Person
instanceof/prototype.isPrototypeOf
继承
// 第一步,子类的构造函数调用父类的构造函数
function Rectangle() {
Shape.call(this);
}
// 第二步,子类继承父类的原型
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
模块
立即执行函数
定时器
var obj = {
x: 2,
y: function () {
console.log(this.x);
}
};
setTimeout(obj.y.bind(obj), 1000);
setTimeout(function () {
obj.y();
}, 1000);
防抖
function debounce(fn, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
function debounce(fn) {
let timer = null;
return function() {
clearTimeout(timer);
timer = setTimeout(() => {
fn.call(this, arguments);
}, 1000);
}
}