I want to call child object method 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();
Why when I use this.sleep()
everything works fine, but when I use _self.sleep()
( _self
variable has this
value) I get error? Why _self
and this
inside the test()
function are not same?
The this
reference stored in self
is different from the this
reference you call inside the anonymous function you assigned to test()
. The point is that the this
scope of the function you're creating and assigning to Hamster.prototype
is an empty object. It's so because you used the new
keyword.
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();
}
}
You're confused about how prototypes work.
You probably want nothing more than
Hamster.prototype = {
test: function() {
this.sleep();
}
};
What you are doing is creating a new object for the prototype. The _self
variable you are setting is not pointing to the this
of individual Hamster objects, but rather to the this
of the new prototype object you are creating, which is lost to the world.
Let's write it with a function which returns the two things, letting us compare them more easily
function Constructor() {}
Constructor.prototype = new function () {
var foo = this;
this.bar = function () {
return {"this": this, "foo": foo};
};
};
var instance = new Constructor(),
o = instance.bar();
And now test what we've got
o.this === instance; // true
o.foo === instance; // fase
// so what is o.foo ?
o.foo === Constructor.prototype; // true
What does this tell us?
instance
, this
refers to that instance new
, then this
refers to a new object instance created by the new
; in this case it is the object we've then set as the prototype for Constructor
When are these references set?
this
in instance.bar
is only set when instance.bar
is actually invoked this
from the new function () { ... }
is set immediately as it is created and does not change after that (you've basically used an IIFE ), it is also what is returned by the new
so what the Constructor.prototype
gets set to in this example _self是您定义的匿名函数之外的局部变量,您没有通过它,因此未在内部定义
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.