原型和原型链
构造函数
构造函数就是能够构造出对象的函数。所有 js 中的函数从出生就自带一个 prototype 的属性,prototype 从出生就自带一个 constructor,constructor 从出生时它的值就是函数自身
构造对象的两种方式:
构造函数+prototype
和class
;构造函数中,实例成员就是构造函数内部通过
this
添加的成员,如下;
js
//Person是一个构造函数
function Person(name, age) {
this.name = name;
this.age = age;
this.say = function () {
console.log("我是人");
};
}
- 在构造函数上添加的成员就成为静态成员,如下;
js
Person.height = 175;
- 通过
prototype
添加的成员是实例成员,不是静态成员,也就是只要是实例化的对象都可以访问到,如下;
js
var p1 = new Person("张三", 25); //实例化对象
Person.prototype.weight = "70kg";
console.log(p1.weight); //70kg
console.log(Person.weight); //undefined
静态成员
只能通过构造函数
进行访问;
js
console.log(Person.height); //输出165
console.log(p1.height); //输出undefined
实例成员
只能通过实例对象
进行访问;
js
console.log(p1.name); //输出张三
p1.say(); //输出我是人
console.log(Person.age); //输出undefined
Person.say(); //报错,Person.say is not a function
constructor
prototype
https://zhuanlan.zhihu.com/p/409863266
__proto__
instanceof
https://blog.csdn.net/weixin_47267628/article/details/126789928
Object.getPrototypeOf(o)
对象、原型、实例 三者关系图
js
person = new Person();
Person.prototype == person.__proto__;
Person.prototype == Object.getPrototypeOf(person);
Object.getPrototypeOf(person) == person.__proto__;
Person.prototype.constructor = Person;
Person.prototype.constructor == person.constructor;
Person == person.constructor;
toString()
继承
new 原理
new
命令的作用,就是执行构造函数,返回一个实例对象。使用new
命令时,它后面的函数依次执行下面的步骤。
- 创建一个空对象,作为将要返回的对象实例。
- 将这个空对象的原型,指向构造函数的
prototype
属性。 - 将这个空对象赋值给函数内部的
this
关键字。 - 开始执行构造函数内部的代码。
也就是说,构造函数内部,this
指的是一个新生成的空对象,所有针对 this
的操作,都会发生在这个空对象上。构造函数之所以叫“构造函数”,就是说这个函数的目的,就是操作一个空对象(即 this
对象),将其“构造”为需要的样子。
如果构造函数内部有 return
语句,而且 return
后面跟着一个对象,new
命令会返回 return
语句指定的对象;否则,就会不管 return
语句,返回 this
对象。
new
命令简化的内部流程,可以用下面的代码表示。
js
function _new(/* 构造函数 */ constructor, /* 构造函数参数 */ params) {
// 将 arguments 对象转为数组
var args = [].slice.call(arguments);
// 取出构造函数
var constructor = args.shift();
// 创建一个空对象,继承构造函数的 prototype 属性
var context = Object.create(constructor.prototype);
// 执行构造函数
var result = constructor.apply(context, args);
// 如果返回结果是对象,就直接返回,否则返回 context 对象
return typeof result === "object" && result != null ? result : context;
}
// 实例
var actor = _new(Person, "张三", 28);