首先js不是基于类的,而是通过构造函数和原型链实现的,ES6中提供了语法糖Class
构造函数
特点:函数名首字母大写,内部使用this对象,使用new来调用构造函数。
function Person(){ this.name = 'keith'; } var boy = new Person(); console.log(boy.name); //'keith'
缺点:同一构造函数的对象之间无法共享属性或方法。
因此就有了prototype
prototype
js中每个数据类型都是对象(除了null和undefined),而每个对象都继承自另外一个对象,后者称为“原型”(prototype)对象,只有null除外,它没有自己的原型对象。
原型对象上的所有属性和方法都会被对象实例所共享。每一个构造函数都有一个prototype属性
function Person(name,height){ this.name=name; this.height=height; } Person.prototype.hobby=function(){ return 'watching movies'; } var boy=new Person('keith',180); var girl=new Person('rascal',153); console.log(boy.name); //'keith' console.log(girl.name); //'rascal' console.log(boy.hobby===girl.hobby); //true
当某个对象实例没有该属性和方法时,就会到原型对象上去查找。如果实例对象自身有某个属性或方法,就不会去原型对象上查找。
boy.hobby=function(){ return 'play basketball'; } console.log(boy.hobby()); //'play basketball' console.log(girl.hobby()); //'swimming'
function A(){}; var a=new A(); console.log(a.constructor); //A() console.log(a.constructor===A.prototype.constructor);//true
上面代码中,a是构造函数A的实例对象,但是a自身没有contructor属性,该属性其实是读取原型链上面的
A.prototype.constructor属性。
参考https://www.cnblogs.com/douyage/p/8630529.html
https://blog.csdn.net/cc18868876837/article/details/81211729