简体   繁体   English

我可以使用原型向外部类添加非静态方法吗?

[英]can I add non static method to external class using prototypes?

Can I add using prototypes function for a class instance?我可以为类实例添加 using 原型函数吗?

so I'll be able to use this or __proto__ keyword inside my method, for example:所以我将能够在我的方法中使用this__proto__关键字,例如:

class PersonClass {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  sayHello() {
    console.log(`hello, my name is ${this.name} and I'm a ${this.type}`);
  }
}

PersonClass.prototype.type = "human";
PersonClass.prototype.PrintType = () => {
  console.log(`I'm a ${PersonClass.prototype.type}`);
};

const aria = new PersonClass("Ned Stark");
aria.sayHello();
aria.PrintType();

this code works of course, but I wish to add something like这段代码当然有效,但我想添加类似的东西

PersonClass.prototype.SayHello2 = () => {
  console.log(this.name, caller.__proto__.name);
};

which of course fails.这当然失败了。

is it even possible?甚至有可能吗?

Your SayHello2 should be a non-arrow function to access the properties you are looking for:你的SayHello2应该是一个非箭头函数来访问你正在寻找的属性:

PersonClass.prototype.SayHello2 = function () {
  console.log(this.name, this.type);
};

which produces:它产生:

"Ned Stark",  "human" 

Don't forget you also have access to the constructor property of an instance as well, allowing you to access everything associate with your classes.不要忘记您还可以访问实例的constructor属性,允许您访问与您的类相关的所有内容。

This should works:这应该有效:

    PersonClass.prototype.SayHello2 = function() {
      console.log(this.name);
    };

    aria.SayHello2(); // "Ned Stark"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以使用EmberJS mixins添加(静态)类方法 - Can I add (static) class methods using EmberJS mixins 创建ES6-class实例后,是否可以立即将实例绑定到非静态方法? - Can I bind the instance to non-static method immediately after creating instance of ES6-class? 我如何使用非静态方法@在GWT中使用window.addEventListener('message'〜 - How can I use non-static-method @ Using window.addEventListener('message'~ in GWT 如何使用javascript调用用代码编写的非静态方法? - How can I call a non static method written in code behind using javascript? 使用原型的Javascript类系统 - Javascript class system using prototypes 您可以在React组件类中添加外部函数作为方法吗? - Can you add an external function as a method in a React component class? 我可以将方法添加到HTMLElement的自定义类中吗 - Can I add method to a custom class of an HTMLElement 在JavaScript class中初始化static变量时可以使用非静态变量吗? - Can I use non-static variables when initializing static variables in a JavaScript class? 如何注释该参数是 class 并具有某些 static 方法? - How can I annotate that argument is a class and has certain static method? 如何使用点表示法在JavaScript中向数组和对象原型添加console.log方法? - How do you add a console.log method on to arrays and objects prototypes in JavaScript using the dot notation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM