原型链(图):
原型:
不使用原型
function People(name, age) {
this.name = name;
this.age = age;
this.speak = function () {
console.log(this.name + ": 在说话");
}
}
var p1 = new People("张三", 18);
console.log(p1);
p1.speak();
var p2 = new People("李四", 28);
console.log(p2);
p2.speak();
console.log(p1.speak === p2.speak); // false
使用原型
function People(name, age) {
this.name = name;
this.age = age;
}
// 两种原型声明方式:
People.prototype.legs = 2;
People.prototype.speak = function () {
console.log(this.name + ": 在说话");
}
People.prototype = {
consotructor: People,
speak: function () {
console.log(this.name + ": 在说话");
}
}
var p1 = new People("张三", 18);
console.log(p1);
p1.speak();
var p2 = new People("李四", 28);
console.log(p2);
p2.speak();
console.log(p1.speak === p2.speak) // false
console.log(p1.__proto__ === People.prototype); // true
es5中实现继承
function People(name,age){
this.name = name;
this.age = age;
}
People.prototype.legs = 2;
People.prototype.speak = function(){
console.log(this.name + ": 在说话");
}
function Student(name,age,id){
// 属性继承
People.call(this,name,age);
// 添加自己独有的属性
this.id = id;
}
// 原型继承
Student.prototype = Object.create(People.prototype);
Student.prototype.goToSchool = function(){
console.log("上学校");
}
var s1 = new Student("小小",12,541010011);
s1.speak();
s1.goToSchool();
es6新继承语法
class People {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
console.log(this.name + ": 在说话");
}
}
var p1 = new People("张三", 18);
console.log(p1);
p1.speak();
class Student extends People {
constructor(name, age, id) {
super(name, age);
this.id = id;
}
}
var s1 = new Student("小小", 12, 541010011);
console.log(s1);
s1.speak();
js中的对象都有一个__proto__的属性,叫做原型
反例
var abc = Object.create(null);
console.log(abc); // 没有
闭包、reduce方法
// 没有使用闭包
function sum(arr) {
return arr.reduce(function (x, y) {
return x + y;
});
}
var reduce = sum([1, 2, 3, 4, 5])
console.log(reduce); // 15
function lazy_sum(arr) {
var abc = 100;
return function () {
return arr.reduce(function (x, y) {
return x + y;
});
}
}
var temp1 = lazy_sum([1, 2, 3, 4, 5]);
var temp2 = lazy_sum([1, 2, 3, 4, 5]);
console.log(temp1 === temp2); // false
// 隔了很多代码
temp1();
function count() {
var arr = [];
for (var i = 1; i <= 3; i++) {
arr.push((function (x) {
return function () {
return x * x;
}
})(i));
}
return arr;
}
var results = count();
var f1 = results[0];
console.log(f1()); // 1
var f2 = results[1];
console.log(f2()); // 4
var f3 = results[2];
console.log(f3()); // 9