Rob*_*bin 3 javascript prototype
我有一个类,并给它的原型几个子对象,以方便命名空间.这些子对象有方法.我无法弄清楚如何this在这些方法中使用来访问使用构造函数设置的属性.
我有一种感觉bind,call并且apply以某种方式参与其中,但是我很难理解那些做什么,以及所有这些OOP-ness的工作原理.有很多资源,但它们都是太低级别,或者高级别我不理解它们.谢谢!
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
Run Code Online (Sandbox Code Playgroud)
无论何时你打电话给表格foo.bar(),this里面bar都会参考foo.除非您将函数绑定到特定值.bind,或使用ES6中的新"箭头"函数.
因此,一种解决方案可以是将方法绑定到特定实例.但是,在调用构造函数之前,实例不存在.这意味着你必须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)
};
}
Run Code Online (Sandbox Code Playgroud)
或者使用新的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;
}
};
}
Run Code Online (Sandbox Code Playgroud)
这意味着每个实例都有自己的子对象副本.
如果你想在原型上定义方法,你总是必须通过.call或传递接收器.apply:
foo.subObject1.method1.call(foo);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,根本没有将它分配给原型的好处,你可以只有一个接受object(method1(foo))的简单函数.
| 归档时间: |
|
| 查看次数: |
786 次 |
| 最近记录: |