我一直在努力让自己的头脑能够吸引人并且不会陷入其中.我已经阅读过JavaScript Getters and Setters和Defining Getters and Setters而且还没有得到它.
有人可以明确说明:
我想在JS中创建一个使用本机getter和setter的类.我知道我可以为对象创建getter/setter,如下所示:
var obj = {
get value(){
return this._value;
},
set value(val){
this._value = val;
}
}
Run Code Online (Sandbox Code Playgroud)
我也知道我可以this.__defineGetter__在一个类/函数中使用,但是MDN说使用__defineGetter__()等是不合适的.
是否有更好的方法将getter和setter添加到js类中:
function class(){
};
class.prototype = {
get value(){
//....
}
Run Code Online (Sandbox Code Playgroud)
?
我最近通过编写一些gnome shell扩展来学习javascript,因此我对Javascript的理解已经被我在gnome-shell javascript源中观察到的例子所塑造.我有一种感觉,我一直在理解错误的课程,只是想要一些澄清.
我已经编写了一些自己的子类,并且在每种情况下我只是通过遵循gnome-shell javascript源代码中的类似代码来定义它们:
Subclass = function() {
this._init.apply(this,arguments);
}
Subclass.prototype = {
__proto__: Superclass.prototype,
_init: function() {
Superclass.prototype._init.call(this);
},
// add other methods of Subclass here.
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我认为这是制作课程的标准方式,Subclass基本上是Superclass额外的.我假设每个对象都有一个_init方法.
我最近尝试应用相同的方法来创建a的子类Clutter.Actor(重要的是它不是GNOME-shell定义的类),并且意识到上面的子类化对象的方式不是标准.首先,并非每个班级都有_init我所假设的功能; 这只是GNOME-shell在他们的javascript类中完成的事情.
所以,我的问题是:
Subclass.prototype = new Superclass()而不是做Subclass.prototype = { __proto__:Superclass.prototype, define_prototype_methods_here }方法,但我的想法是,如果gnome-shell一直使用它,必须有一些方法吗?Superclass.prototype._init.call(this)同在Subclass._init,以确保在Subclass.prototype得到所有Superclass(我在我的定义中添加的方法/属性Subclass.prototype),如果Superclass没有_init函数(即它是否有一些我调用的等效构造函数)?我真的很困惑这一切所以请原谅我,如果我的问题没有多大意义; 这是因为我的误解和困惑的程度!
编辑:澄清: - …
在像这样的对象中使用"get"时,"get"起作用:
var people = {
name: "Alex",
get sayHi() {
return `Hi, ${this.name}!`
}
};
var person = people;
document.write(person.sayHi);
Run Code Online (Sandbox Code Playgroud)
但是使用函数我会收到错误.如何在这样的函数中使用Getters和Setter?
function People2() {
this.name = "Mike";
get sayHi() {
return `Hi, ${this.name}!`;
}
};
var user = new People2();
document.write(user.sayHi);Run Code Online (Sandbox Code Playgroud)
所以我打算建立一个小型图书馆,但这个问题有多种应用。
我想知道使用构造函数和类创建对象之间的区别。例如,这段代码...
function Thing (name) {
this.name = name;
this.doSomething = function (){};
alert("A new thing was created.");
}
var x = new Thing();
Run Code Online (Sandbox Code Playgroud)
...以及这段代码...
class Thing {
constructor(name) {
this.name = name;
alert("A new thing was created.");
}
doSomething() {}
}
var x = new Thing();
Run Code Online (Sandbox Code Playgroud)
...产生相同的结果,但以不同的方式。
但是,我更熟悉构造函数,但我需要使用 getter 和 setter 创建对象。尽管MDN将类定义为“语法糖”,但我不知道是否可以使用构造函数定义 getter 和 setter。
还有,女巫的性能是最好的?
注意:我不是指使用Thing.prototype. 我想知道构造函数和类之间的区别。