Sha*_*313 1 javascript prototype class
javascript 中没有实际的类。但你必须利用你所得到的东西。
让我们以“类”为例:
var example = function (string) {
this._self = string;
}
Run Code Online (Sandbox Code Playgroud)
通过以上内容,您可以执行以下操作:
var ex = new example("Hello People."),
display = ex._self; // returns "Hello People."
Run Code Online (Sandbox Code Playgroud)
我想通过使用类似的东西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"));
Run Code Online (Sandbox Code Playgroud)
我想做的是将display函数作为“公共函数”添加到示例函数中。我可能做错了什么。
具有原型的不是对象,而是用于创建对象的函数:
var example = function (string) {
this._self = string;
}
example.prototype.display = function (a) {
return a;
};
Run Code Online (Sandbox Code Playgroud)