1

javascript 中没有实际的类。但是你必须用你得到的东西工作。

让我们以“类”为例:

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函数作为“公共函数”添加到示例函数中。我可能做错了什么。

4

5 回答 5

4

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

var example = function (string) {
  this._self = string;
}

example.prototype.display = function (a) {
  return a;
};
于 2013-01-19T01:02:43.717 回答
3

因为没有原型showExample- 它只是example. 尝试这样做:example.prototype.display = function (a) {}它会起作用。

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

于 2013-01-19T01:01:36.673 回答
3

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

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

于 2013-01-19T01:01:44.433 回答
3

您可以修改为 showExample ..的构造函数

前任。

showExample.constructor.prototype.display = function (a) {
  return a;
}
于 2013-01-19T01:05:46.500 回答
1

在你的情况下 showExample 是一个例子的对象......

采用

example.prototype.display = function(a)...
于 2013-01-19T01:03:15.400 回答