I have tried hard looking for a solution for this issue, found kind of strange that this question wasn't asked before here:
var A = function(){
this.timeLength = 5;
}
A.prototype.info = {
type: 'video',
duration: function(){ return this.timeLength;}
}
var AInst = new A();
AInst.info.duration(); // is giving undefined
How to write this in the way to make it access the instance property?
A couple of things here:
this.timelength
in your duration method is referring to A.prototype.info
, not A.prototype
That being said, you could change your code by either invoking AInst.info.duration()
on the last line, or just assign .type
and .duration
to A.prototype
:
var A = function(){
this.timeLength = 5;
}
A.prototype = {
type: 'video',
duration: function(){ return this.timeLength;}
}
var AInst = new A();
AInst.duration();
'this' is wherever 'this' is called. so... function(){ this } 'this' is the function. You could use the window object. If needed, you can pass a 'this' as an argument to another function... just don't call it 'this'... that'll get ugly fast. 'self' is a common name for copies of a 'this'
window.onload = doThis;
function doThis() {
var A = function(){
window.timeLength = 5;
}
A.prototype.info = {
type: 'video',
duration: function(){ return window.timeLength;}
}
var AInst = new A();
AInst.info.duration(); // is giving undefined
console.log(AInst.info.duration());
}
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.