new一个对象
/**fn:构造函数,arg:参数*/const create = (fn, ...arg) => {const obj = Object.create(fn.prototype) /** 创建一个对象 并将对象的原型指向构造函数 */const ret = fn.call(obj, ...arg) /** 执行构造函数将函数this指向创建的对象并传arg参数 */return typeof ret === 'object' ? ret : obj /** 如果ret 有返回值 返回ret 否则 返回obj*/}function A(a){this.a = areturn {a:3}}let f = create(A,1)console.log(f) //{a:3}
- 创建一个对象 将对象的proto指向构造函数
- 调用构造函数将函数this指向该对象
- 如果函数有返回值 返回 函数返回值 否则返回该对象
构造函数
function A(name){this.A = name /** 公有属性 */let B = 'hello' /** 私有属性 */function sayName(){alert(that.name);} /** 私有方法 */}A.prototype.say = function(){console.log('原型方法')}A.alertName = ()=>{console.log('静态方法')}A.c = 'world' /** 静态属性 */
继承
原型继承
继承构造函数的方法和公有属性
function A(){}A.prototype.mySay = function(){console.log('hello A')}function B(){}B.prototype = new A()B.prototype.constructor = B /** 修改为B指向 */const b = new B()b.mySay() /** hello A */
构造函数继承
继承函数的私有属性
function A(name){this.name = name}function B(...args){A.call(this,...args)}const b = new B('jack') //{name:'jack'}
寄生组合继承
通过Object获取原型
function A(){this.name = name}A.prototype.mySay = function(){console.log('hello A')}function B(){A.call(this,...args)}B.protype = Object.create(A.prototype)B.prototype.constructor = B
class 继承
function A(age){this.age = age}A.prototype.sayAge = function(){console.log(this.age)}class B extends A{constructor(...arg){super(...arg)}}const b = new B(18)console.log(b)b.sayAge()
