跳到主要内容

原型与继承

最基础的 this

function P() {
this.foo1 = function () {
console.log(this); // 如果直接P(),再执行函数,这里的this是window
};
this.foo2 = () => {
console.log(this); // 如果直接P(),再执行函数,这里的this是P的this,也是window
};
}

// 但是new了 P后

let p = new P();
// P中相当于

function P() {
p.foo1 = function () {
console.log(this); // 执行后才能决定
};
p.foo2 = () => {
console.log(p); // 箭头函数的this是P的this
};
}

p.foo1();
p.foo2();
打印出来都是p;
new绑定成功;

控制台打印结果
P {
foo1:
foo2:
}

这里有个小坑,P是构造函数的名字,打印出来的是实例
要打印P当然打印的是函数体啦

new 操作符拷贝 prototype

function Fn() {}
Fn.prototype.add = function () {
this.count++;
console.log(this.count);
};

Fn.prototype.count = 0;
let fn1 = new Fn();
// new的时候会把 prototype 上的变量和方法拷贝到自己身上!由自己管理
console.log(fn1.count); // 0
fn1.add(); // 1
fn1.add(); // 2
let fn2 = new Fn();
console.log(fn2.count); // 0
fn2.add(); // 1
console.log(fn1);
// {count: 2}
console.log(fn1.__proto__);
// {count: 0}

原型链基础 1

let obj = {};
console.log(obj.__proto__); // Object.prototype
console.log(obj.prototype); // undefined
console.log(Object.prototype); //Object.prototype

原型链基础 2

function Person(name) {
this.name = name;
}
var p2 = new Person("king");
console.log(p2.__proto__); //Person.prototype
console.log(p2.__proto__.__proto__); //Object.prototype
console.log(p2.__proto__.__proto__.__proto__); // null
console.log(p2.__proto__.__proto__.__proto__.__proto__); //null后面没有了,报错
console.log(p2.__proto__.__proto__.__proto__.__proto__.__proto__); //null后面没有了,报错
console.log(p2.constructor); //Person
console.log(p2.prototype); //undefined p2是实例,没有prototype属性
console.log(Person.constructor); //Function 一个空函数
console.log(Person.prototype); //打印出Person.prototype这个对象里所有的方法和属性
console.log(Person.prototype.constructor); //Person
console.log(Person.prototype.__proto__); // Object.prototype ****因为是个对象
console.log(Person.__proto__); //Function.prototype
console.log(Function.prototype.__proto__); //Object.prototype
console.log(Function.__proto__); //Function.prototype
console.log(Object.__proto__); //Function.prototype
console.log(Object.prototype.__proto__); //null ******但是这个对象没有了

除了 Object.prototype,所有 prototype 的 proto 都是 Object.prototype

所有构造函数的 proto 都是 Function 的 prototype

先 new 后设置 prototype

找不到直接报错

function Person() {}

var friend = new Person();

Person.prototype = {
constructor: Person,

name: "Nicholas",

age: 29,

job: "Software Engineer",

sayName: function () {
alert(this.name);
},
};