javascript - Difference in calling method on object or passing object as function argument -
what difference in calling method on object or passing object function argument, , accordingly how pass argument in method call? putting placeholder argument didn't produced desired effect. have iterate trough property names(not values) , compare given argument (as property name) real property name in object?
here heavily commented piece of code, because i'm curious happening.
// create object constructor function foo(prop1, prop2) { this.prop1 = prop1; this.prop2 = prop2; // create object method printobjectpropertym // , retreive property value // * there m @ end of property distinguish // method/function name // how can add placeholder/argument in method , // call method on object provided argument (here prop1 or prop2) this.printobjectpropertym = function() { console.log(this.prop1); }; } // instantiate new object bar of foo type var bar = new foo("prop1val", "prop2val"); // create function print object property , take object argument var printobjectproperty = function(object) { console.log(object.prop1); }; // call printobjectproperty bar object argument printobjectproperty(bar); // logs prop1var in console // call bar method printobjectpropertym bar.printobjectpropertym(); // logs prop1val in console
please kind , correct me if wrong in comments, code or pseudocode.
solution
you should use []
notation access object's property name.
create method inside constructor:
function foo(prop1val, prop2val) { this.prop1 = prop1val; this.prop2 = prop2val; this.printproperty = function (name) { if (this.hasownproperty(name)) { console.log(this[name]); } } }
now call it:
var bar = new foo("prop1val", "prop2val"); bar.printproperty("prop1");
Comments
Post a Comment