我有一个类,并为其原型(prototype)提供了几个子对象以方便命名空间。这些子对象有方法。我不知道如何在这些方法中使用 this
来访问使用构造函数设置的属性。
我有一种感觉,bind
、call
和 apply
都以某种方式参与其中,但我很难理解它们的含义这些都是如此,以及所有这些面向对象编程的总体工作原理。资源很多,但要么太低级,要么太高级我看不懂。谢谢!
function Object(
argument1,
argument2
){
this.property1 = argument1;
this.property2 = argument2;
}
Object.prototype = {
subObject1 : {
method1 : function(){
return this.property1;
}
},
subObject2 : {
method1 : function(){
return this.property2;
}
}
}
var foo = new Object(11, 22);
var bar = new Object(33, 44);
console.log(foo.subObject1.method1()); //I'd like this to return 11
console.log(foo.subObject2.method1()); //I'd like this to return 22
console.log(bar.subObject1.method1()); //I'd like this to return 33
console.log(bar.subObject2.method1()); //I'd like this to return 44
最佳答案
每当您调用 foo.bar()
形式时,bar
内的 this
都会引用 foo
. 除非您使用.bind
将函数绑定(bind)到特定值,或者使用ES6中新的“箭头”函数。
因此,一种解决方案是将方法绑定(bind)到特定实例。但是,在调用构造函数之前,该实例并不存在。这意味着您必须在构造函数内创建 subObjectX
:
function MyObject(argument1, argument2) {
this.property1 = argument1;
this.property2 = argument2;
this.subObject1 = {
method1: function(){
return this.property1;
}.bind(this)
};
this.subObject2 = {
method1: function(){
return this.property2;
}.bind(this)
};
}
或者使用新的 ES6 箭头函数;它们从创建它们的上下文中获取this
(与普通函数不同):
// ES6 only!
function MyObject(argument1, argument2) {
this.property1 = argument1;
this.property2 = argument2;
this.subObject1 = {
method1: () => {
return this.property1;
}
};
this.subObject2 = {
method1: () => {
return this.property2;
}
};
}
这意味着每个实例都有自己的子对象副本。
如果您想在原型(prototype)上定义方法,则始终必须通过 .call
或 .apply
传递接收者:
foo.subObject1.method1.call(foo);
在这种情况下,将其分配给原型(prototype)根本没有太大好处,您可以只拥有一个接受该对象的简单函数(method1(foo)
)。
关于javascript - 在嵌套的 Prototype 子对象中使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29130193/