`this.method` 和 `super.method` 在 TypeScript 中的区别是什么?

huangapple go评论86阅读模式
英文:

The difference between this.method and super.method in typescript?

问题

请查看badRequest方法。

英文:

I have BaseClass and InheritClass like this

export class BaseClass {
  public getDevice() {
  }
}

export class InheritClass extends BaseClass {
  constructor {
    super();
  }
  public devices() {
   // this.getDevice() // work in Nextjs project but undefined in Expressjs project
   // super.getDevice() // work both
  }
}

Can you explain why?
I'm using typescript.

tsconfig.json in Express project

"target": "ES2018",
"module": "commonjs",
"lib": ["es6", "dom"],

tsconfig.json in Nextjs project

"target": "esnext",
"lib": [
  "dom",
  "dom.iterable",
  "esnext"
],
"module": "esnext",

Below are codes in my project with Express

import { injectable } from 'inversify';
import "reflect-metadata";
import { Request, Response, NextFunction } from "express";
import rateLimit from 'express-rate-limit';
import { ResponseData } from "@/interface/responseData";
import { generalMsg } from "@/msg";

@injectable()
export class BaseMiddleware {
  private limiter = rateLimit({
    windowMs: 1 * 60 * 1000, // giới hạn 1 phút
    max: 1000, // tối đa 1000 requests trong 1 phút
  });
  public async execute(req: Request, res: Response, next: NextFunction): Promise<void | {}> {
    try {
      this.limiter(req, res, () => {
        next();
      });
    } catch (error) {
      console.error(error);
    }
  }
  protected badRequest(error: {details: any}, res: Response){
    const responseData = new ResponseData(
      null,
      generalMsg.error.request,
      false,
      error.details
    );
    return res.status(400).json(responseData.toJson());
  }
}

import "reflect-metadata";
import { injectable } from "inversify";
import { Request, Response, NextFunction } from "express";
import Joi from "joi";
import { BaseMiddleware } from "@middleware/base.middleware";

@injectable()
export class DeviceMiddleware extends BaseMiddleware {  
  constructor() {
    super();
  }
  public async addDevice(
    req: Request,
    res: Response,
    next: NextFunction
  ): Promise<void | {}> {
    try {
      const schema = Joi.object({
        userId: Joi.number().allow(null),
        deviceToken: Joi.string().required(),                
      });
      const validateSchema = await schema.validateAsync(req.body);
      next();
    } catch (error: any) {
      if (error) {
        return super.badRequest(error, res);
      }
    }
  }
}

Please take a look on badRequest method.

答案1

得分: 1

this.getDevice() 指向子类,而 super.getDevice() 始终指向父类。

class BaseClass {
  getDevice() {
    return 'base';
  }
}

class InheritClass extends BaseClass {
  devices() {
    console.log(this.getDevice());  // inherit
    console.log(super.getDevice()); // base
  }
  
  getDevice() {
    return 'inherit';
  }
}

const instance = new InheritClass();

instance.devices();
英文:

The difference is better visible if both classes have the getDevice method.

this.getDevice() will point to the child class while super.getDevice() will always point to the parent class.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

class BaseClass {
  getDevice() {
    return &#39;base&#39;;
  }
}

class InheritClass extends BaseClass {
  devices() {
    console.log(this.getDevice());  // inherit
    console.log(super.getDevice()); // base
  }
  
  getDevice() {
    return &#39;inherit&#39;;
  }
}

const instance = new InheritClass();

instance.devices();

<!-- end snippet -->

答案2

得分: 0

这取决于你使用的确切内容
super 就像请求父类

所以如果你有两个类

class Parent
{
    sayHi()
    {
        console.log('Hi');
    }
}

class Child extends Parent
{
    sayHi()
    {
        console.log('Yo');
    }

}

你可以单独调用它们,因为孩子从父类那里学到了除了私有或受保护之外的一切
super.someMethod(); 或者扩展父类并添加一些额外的东西

const person = new Child();
person.sayHi();
//输出:
//'Yo';

person.super.sayHi();
//输出:
//'Hi'

另外,你的子类可以做与父类相同的事情,但可以添加额外的内容,比如

class Child extends Parent
{
    sayHi()
    {
        super.sayHi();
        console.log('Whats up?');
    }

}

const person = new Child();

person.sayHi();
//输出:
//'Hi
//Whats up?'
英文:

this depends on exactly what you use
super is like asking for parent

So if you have 2 classes

class Parent
{
    sayHi()
    {
        console.log(&#39;Hi&#39;);
    }
}

class Child extends Parent
{
    sayHi()
    {
        console.log(&#39;Yo&#39;);
    }

}

You can call both by it self since kids learn from parent's everything thats not private or protected from them
super.someMethod(); or extend parent and add something extra to it

const person = new Child();
person.sayHi();
//Output:
//&#39;Yo&#39;;

person.super.sayHi();
//Output:
//&#39;Hi&#39;

Also your child class can do same as parent but with extra things like

class Child extends Parent
{
    sayHi()
    {
        super.sayHi();
        console.log(&#39;Whats up?&#39;);
    }

}

const person = new Child();

person.sayHi();
//Output:
//&#39;Hi
//Whats up?&#39;


</details>



# 答案3
**得分**: -1

this.getDevice(): 这指的是当前类(InheritClass)的getDevice()方法。当你调用this.getDevice()时,它会查找InheritClass本身定义的getDevice()方法。如果在InheritClass中未定义getDevice()方法,它会在父类中查找,直到找到该方法或达到继承层次的顶部。

super.getDevice(): 这指的是父类(BaseClass)的getDevice()方法。当你调用super.getDevice()时,它直接调用父类的getDevice()方法,跳过当前类(InheritClass)中可能存在的方法覆盖。这允许你显式访问和调用父类中的方法实现。

<details>
<summary>英文:</summary>

this.getDevice(): This refers to the getDevice() method of the current class, which is InheritClass. When you invoke this.getDevice(), it looks for the getDevice() method defined within InheritClass itself. If getDevice() is not defined in InheritClass, it will search for the method in the parent classes until it finds the method or reaches the top of the inheritance hierarchy.

super.getDevice(): This refers to the getDevice() method of the parent class, which is BaseClass. When you invoke super.getDevice(), it directly calls the getDevice() method of the parent class, bypassing any potential method overrides in the current class (InheritClass). This allows you to explicitly access and invoke the method implementation from the parent class.

</details>



huangapple
  • 本文由 发表于 2023年6月8日 22:46:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433068.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定