new一个对象

  1. /**
  2. fn:构造函数,
  3. arg:参数
  4. */
  5. const create = (fn, ...arg) => {
  6. const obj = Object.create(fn.prototype) /** 创建一个对象 并将对象的原型指向构造函数 */
  7. const ret = fn.call(obj, ...arg) /** 执行构造函数将函数this指向创建的对象并传arg参数 */
  8. return typeof ret === 'object' ? ret : obj /** 如果ret 有返回值 返回ret 否则 返回obj*/
  9. }
  10. function A(a){
  11. this.a = a
  12. return {a:3}
  13. }
  14. let f = create(A,1)
  15. console.log(f) //{a:3}
  1. 创建一个对象 将对象的proto指向构造函数
  2. 调用构造函数将函数this指向该对象
  3. 如果函数有返回值 返回 函数返回值 否则返回该对象

    构造函数

    1. function A(name){
    2. this.A = name /** 公有属性 */
    3. let B = 'hello' /** 私有属性 */
    4. function sayName(){
    5. alert(that.name);
    6. } /** 私有方法 */
    7. }
    8. A.prototype.say = function(){
    9. console.log('原型方法')
    10. }
    11. A.alertName = ()=>{
    12. console.log('静态方法')
    13. }
    14. A.c = 'world' /** 静态属性 */

    继承

    原型继承

    继承构造函数的方法和公有属性

  1. function A(){}
  2. A.prototype.mySay = function(){console.log('hello A')}
  3. function B(){}
  4. B.prototype = new A()
  5. B.prototype.constructor = B /** 修改为B指向 */
  6. const b = new B()
  7. b.mySay() /** hello A */

构造函数继承

继承函数的私有属性

  1. function A(name){
  2. this.name = name
  3. }
  4. function B(...args){
  5. A.call(this,...args)
  6. }
  7. const b = new B('jack') //{name:'jack'}

寄生组合继承

通过Object获取原型

  1. function A(){
  2. this.name = name
  3. }
  4. A.prototype.mySay = function(){console.log('hello A')}
  5. function B(){
  6. A.call(this,...args)
  7. }
  8. B.protype = Object.create(A.prototype)
  9. B.prototype.constructor = B

class 继承

  1. function A(age){
  2. this.age = age
  3. }
  4. A.prototype.sayAge = function(){
  5. console.log(this.age)
  6. }
  7. class B extends A{
  8. constructor(...arg){
  9. super(...arg)
  10. }
  11. }
  12. const b = new B(18)
  13. console.log(b)
  14. b.sayAge()