javascript - this is undefined while trying to inherit prototype -
i trying add prototype dynamically reason keyword return undefined
when try inherit prototype
. when run same code on browser console works fine. why not working node.js?
i have included full code @ end of question.
my main issue happens here:
let postobj = function(){ this.data = post; this.originalindex = i; }; //postobj.prototype = postproto; // have same result postobj.prototype = object.create(postproto); //postobj.data = post; _self.posts.push(new postobj());
when try access this
inside prototype method return undefined. example postproto
has method id
looks this.data._id
. can see have set constructors postobj
, why not being passed prototype?
please tell me whats wrong here.
full code:
const postprototype = { id: (){ return this.data._id; }, title: (){ return this.data.title; } } function fetchposts(){ this.posts = []; this.rawposts = [ {_id: '1', title: 'in sit amet lorem velit, in dictum lorem'}, {_id: '2', title: 'vestibulum ante ipsum primis in faucibu'}, {_id: '3', title: 'integer vulputate nibh et diam sagittis in dictum mauris dapibus'} ]; this.inheritprototype(); } fetchposts.prototype.inheritprototype = function(){ var _self = this; if(!_.isempty(_self.rawposts)){ _self.rawposts.foreach(function(post, i){ try{ let postobj = function(){ this.data = post; this.originalindex = i; }; //postobj.prototype = postproto; // have same result postobj.prototype = object.create(postprototype); //postobj.data = post; _self.posts.push(new postobj()); }catch(err){ console.log(err); } }); } }; fetchposts.prototype.get = function(){ return this.posts; } var samplefetch = new fetchposts(); samplefetch.get().foreach(function(post, i){ post.id(); // return error: cannot property _id undefined });
first of all, because of try catch block hided error is: "referenceerror: postproto not defined"
. @ top of script, have defined postprototype
variable used postproto
of course undefined.
also, in declaration of postprototype
have used object literal shorthand not properly. should use without :
.
const postprototype = { id (){ return this.data._id; }, title (){ return this.data.title; } }
i have edited code here.
Comments
Post a Comment