什么是原型

一个对象,构造函数上的属性

什么是原型链

Professor.prototype.tSkill = 'JAVA';
function Professor(){}
 
var professor = new Professor();
 
// 原型链继承
Teacher.prototype = professor;
function Teacher(){
  this.mSkill = 'JS/JQ';
}
var teacher = new Teacher();
 
Student.prototype = teacher;
function Student(){
  this.pSkill = 'HTML/CSS';
}
 
var student = new Student();
console.log(student);
student.mSkill;	// JS/JQ
student.tSkill;	// JAVA
// 我没有的属性,可以到我的原型上找,我的原型上没有,再去上一层原型找,这种继承关系叫原型链

原型链的顶端

Object.prototype

constructor

const instance = new Number(3)
Number.prototype.constructor === Number
Number.prototype.__proto__ === Object.prototype
Number.__proto__ === Function.prototype
/*
 * Object是实例,实例没有constructor,会从原型上寻找,即Function.prototype.constructor
 * Object 是new Function()构建出来的
 */
Object.constructor === Function === Function.prototype.constructor;
Object.__proto__ === Function.prototype
 
/*
 * Function 是实例对象,同时 Function 也是构造函数
 */
Function.__proto__ === Function.prototype
 
Function.prototype.__proto__ === Object.prototype //Function.prototype是对象

相关特性

祖先原型上的原始值不能修改

Professor.prototype.tSkill = 'JAVA';
function Professor(){}
 
var professor = new Professor();
 
Teacher.prototype = professor;
function Teacher(){
  this.mSkill = 'JS/JQ';
  this.students = 500;
}
var teacher = new Teacher();
 
Student.prototype = teacher;
function Student(){
  this.pSkill = 'HTML/CSS';
}
 
var student = new Student();
student.students++;
console.log(student.students);
console.log(teacher, student);
student.students; // 501
teacher.students; // 500
可以修改成功但是不能修改上一级原型上的值

案例 :prototype的赋值与重写

1 直接赋值

function Car(){}
Car.prototype.name = 'Mazda';
var car = new Car();
// 给属性赋值
Car.prototype.name = 'Benz';
console.log(car.name); // Benz

2 重写

function Car(){}
Car.prototype.name = 'Mazda';
var car = new Car();
console.log(car.name); // Mazda
// 重写prototype
Car.prototype = {
  name: 'Benz'
};
console.log(car.name); // Mazda

Object.create()

function XX() {};
XX.prototype.num = 1;
var obj1 = Object.create(XX.prototype);
var obj2 = new XX();
console.log(obj1);
console.log(obj2);
prototype_1.webp

可以看到obj1和obj2两对象,内容相同。

Object.create()表示以什么为原型返回实例对象。

new做了什么

实例化对象

调用构造函数的初始化属性和方法

指定实例对象的原型

题目

var obj = Object.create(null);
obj.num = 1
var obj1 = {
	count:2
}
obj.__proto__ = obj1;
console.log(obj.count); //undefined
//不可以自己指定__proto__