向“类”添加属性在JavaScript

Adding a property to a "Class" in JavaScript

本文关键字:属性 JavaScript 添加      更新时间:2023-09-26

javascript中没有实际的类。但是你必须利用你得到的。

让我们以"Class"为例:

var example = function (string) {
  this._self = string;
}
有了上面的代码,你可以这样做:
var ex = new example("Hello People."),
    display = ex._self; // returns "Hello People."

我认为通过使用像example.prototype.newFun = function(){}这样的东西会给那个"类"添加一个新属性。但是它在我的代码中不起作用。

这是我正在测试的完整代码:

var example = function (string) {
  this._self = string;//public, var like, storage
}
var showExample = new example("Hello People");
showExample.prototype.display = function (a) {//code stops here, with error "Uncaught TypeError: Cannot set property 'display' of undefined"
  return a;
}
console.log(showExample._self);
console.log(showExample.display("Bye"));

我要做的是将display函数添加到示例函数中作为"公共函数"。我可能做错了什么

拥有原型的不是对象,而是用来创建对象的函数:

var example = function (string) {
  this._self = string;
}
example.prototype.display = function (a) {
  return a;
};

因为没有showExample的原型-它只是example的一个实例。试着这样做:example.prototype.display = function (a) {},它会工作的。

这里有更多关于JavaScript中的类的内容:

  • 3种定义类的方法

  • 我喜欢Classy处理这个问题的方式,也喜欢CoffeeScript中实现类的方式。

可以修改showExample的构造函数。

showExample.constructor.prototype.display = function (a) {
  return a;
}

您尝试向example (showExample)实例的prototype添加方法。实例没有原型。尝试example.prototype.display = function() {/*...*/};(换句话说,将该方法添加到showExampleconstructorprototype,即example)并再次检查。之后,example的所有实例都"知道"display的方法,或者用你的话来说,display对所有实例都是"公开的"。

可以使用showExample.display = function() {/*...*/};将方法添加到实例。这样,只有showExample知道display的方法。

在你的例子中,showExample是example的对象…

使用

example.prototype.display = function(a)...