如何避免使用;这";在Javascript原型中
这是我的javascript对象,我想知道如何避免在原型中多次使用“this”。我知道原型内在性有很多理论和联系,这可能已经得到了回答,但由于我无法收支平衡,我认为这可能值得再问一个问题如何避免使用;这";在Javascript原型中,javascript,this,prototypal-inheritance,Javascript,This,Prototypal Inheritance,这是我的javascript对象,我想知道如何避免在原型中多次使用“this”。我知道原型内在性有很多理论和联系,这可能已经得到了回答,但由于我无法收支平衡,我认为这可能值得再问一个问题 function shape(smth) { this.a = smth this.b = 2 this.c = 3 } shape.prototype.doCalculus = function () { return this.a * this.b + this.c - (
function shape(smth) {
this.a = smth
this.b = 2
this.c = 3
}
shape.prototype.doCalculus = function () {
return this.a * this.b + this.c - (2 * (this.b + this.c) + this.a);
}
module.exports = shape
如果需要对象的公共成员,则必须从
this
指针引用它们。这就是OO在Javascript中的工作方式。别无选择
如果在一个函数中有许多对同一变量的引用,您可以临时将其放入局部变量中以保存一些引用逻辑(与任何多步引用相同),但您仍必须首先使用this.varName
进行检索
有一种方案在构造函数闭包中使用“私有”成员变量,并且不使用在某些情况下可以使用的原型,这允许您直接引用变量,而无需使用
this
:
function shape(smth) {
var a = smth,
b = 2,
c = 3;
this.doCalculus = function() {
return a * b + c - (2 * (b + c) + a);
}
}
module.exports = shape
对于创建大量实例的对象类型,这可能会消耗更多的内存,因为方法不是存储在共享原型上,而是为每个实例单独创建的。有人认为,在大多数使用中,内存消耗的差异并不重要。你可以避免这样的情况:
function Shape(smth) {
return {"a": smth, "b": 2, "c": 3 };
}
const shape = smth => {
let a = smth,
b = 2,
c = 3;
return {
doCalculus: () => a * b + c - (2 * (b + c) + a)
}
}
console.log(shape(2).doCalculus()); // -5
但我需要补充的是,返回的对象似乎不能很好地使用Shape.prototype.methodname
据我所知,对于最初的示例,您需要执行以下操作:
function Shape(smth) {
return {"a": smth,
"b": 2,
"c": 3,
doCalculus: function () {
return this.a * this.b + this.c - (2 * (this.b + this.c) + this.a);
}
}
因此,您仍然以这种方式结束,并且您已经失去了在
prototype
下分离方法的优势。我还试图让jslint在不勾选“容忍……这个”框的情况下通过我的代码,但我得出结论,只使用这个
要好得多。除了Douglas Crockford之外,所有人似乎都接受它是javascript的一个组成部分。可以通过使用对象来避免在构造函数中使用这个。创建来创建原型链,然后直接在结果对象上声明属性
function Shape(smth) {
var shape = Object.create(Shape.prototype);
shape.a = smth;
shape.b = 2;
shape.c = 3;
return shape;
}
这样就不需要在Shape
函数中使用This
,这意味着我们也不再需要用new
调用它
new Shape(1); // { a: 1, b: 2, c: 3, __proto__: Shape.prototype }
Shape(1); // { a: 1, b: 2, c: 3, __proto__: Shape.prototype }
但是,您仍然需要在原型方法中使用this
来引用正确的实例。如果要避免“this”,可以这样做:
function Shape(smth) {
return {"a": smth, "b": 2, "c": 3 };
}
const shape = smth => {
let a = smth,
b = 2,
c = 3;
return {
doCalculus: () => a * b + c - (2 * (b + c) + a)
}
}
console.log(shape(2).doCalculus()); // -5
您可以使用,尽管它非常不受推荐,并且在中不起作用
函数形状(smth){
此.a=smth;
这是b=2;
这个c=3;
}
Shape.prototype.doCalculus=函数(){
(这个){
返回a*b+c-(2*(b+c)+a);
}
};
console.log(新形状(5.doCalculus())代码>没有引用上下文对象属性的隐式方法。您最好使用with
语句,但它会遇到各种问题,最好避免使用。如果您想要对象的公共成员,则必须从此
指针引用它们。这就是OO在Javascript中的工作方式。别无选择。如果在一个函数中对同一个变量有很多引用,可以暂时将其放入局部变量中以保存一些引用逻辑。@jfriend00,我很乐意接受这个答案:)