我如何从父调用原型子方法
How can I call prototype child method from parent
我想调用子对象方法form prototype object:
function Hamster() {
this.sleep = function(){
console.log('sleep');
}
}
Hamster.prototype = new function(){
var _self = this;
this.test = function(){
this.sleep();
//_self.sleep(); //not working
}
}
lazy = new Hamster();
lazy.test();
为什么当我使用this.sleep()
一切工作正常,但当我使用_self.sleep()
(_self
变量有this
值)我得到错误?为什么test()
函数里面的_self
和this
不一样?
让我们用一个返回两个东西的函数来编写它,让我们更容易比较它们
function Constructor() {}
Constructor.prototype = new function () {
var foo = this;
this.bar = function () {
return {"this": this, "foo": foo};
};
};
var instance = new Constructor(),
o = instance.bar();
现在测试我们得到的
o.this === instance; // true
o.foo === instance; // fase
// so what is o.foo ?
o.foo === Constructor.prototype; // true
这告诉我们什么?
- 当我们从
instance
调用方法时,this
引用该实例 - 当我们用
new
调用一个函数时,this
指的是new
创建的一个新的对象实例;在本例中,它是我们为Constructor
设置的原型对象
何时设置这些引用?
-
instance.bar
中的this
仅在实际调用instance.bar
时设置 -
new function () { ... }
中的this
在创建时立即设置,并且之后不会更改(您基本上使用了IIFE),这也是new
返回的内容,因此Constructor.prototype
在此示例中设置为
存储在self
中的this
引用与您在分配给test()
的匿名函数中调用的this
引用不同。关键是,您正在创建并分配给Hamster.prototype
的函数的this
作用域是一个空对象。这是因为你使用了new
关键字。
Hamster.prototype = new function(){
//Stores the reference to the empty object that's the scope of the anonymous
//function because it was called using the new keyword.
var _self = this;
this.test = function(){
//Works because the this keyword is a reference to Hamster.
this.sleep();
//Does not work because the empty object doesn't have a sleep method.
//_self.sleep();
}
}
你对原型的工作方式感到困惑。
你可能只想要
Hamster.prototype = {
test: function() {
this.sleep();
}
};
你所做的是为原型创建一个新对象。您正在设置的_self
变量不是指向单个仓鼠对象的this
,而是指向您正在创建的新原型对象的this
,该对象丢失在世界中。
_self是您定义的匿名函数之外的一个局部变量并且您没有传递它所以它没有在
相关文章:
- 使用setInterval调用原型函数时出现问题
- Javascript不调用原型方法
- JavaScript–从另一个原型函数调用原型的一个函数
- 通过引用调用原型函数时,类会丢失“this”作用域
- 调用原型函数的元素是什么
- 调用原型的重写方法,然后调用下一个原型的重写方法错误
- 从继承对象的函数调用原型的方法
- 调用原型的函数
- 从回调中调用原型方法
- 通过按钮点击调用原型函数不起作用
- 在保留状态的同时调用原型方法
- 从另一个方法调用原型方法
- 在Javascript上从自身调用原型
- 我如何从父调用原型子方法
- 从父对象调用原型方法不起作用
- HTML5/webcomponents:从模板代码调用原型函数
- 从另一个调用原型方法-得到'undefined'错误
- 未调用原型方法
- 为什么通过setTimeout调用原型函数时会丢失实例信息?
- 从其他原型调用原型中的函数