在对象上调用方法或将对象作为函数参数传递有什么区别,因此我如何在方法调用中传递参数?简单地将占位符作为参数并没有产生预期的效果。我是否必须遍历所有属性名称(不是值),然后将给定参数(作为属性名称)与对象中的真实属性名称进行比较?
这是一段注释很多的代码,因为我很好奇到底发生了什么。
// create object constructor
function Foo(prop1, prop2) {
this.prop1 = prop1;
this.prop2 = prop2;
// create object method PrintObjectPropertyM
// and retreive property value
// * there is M at the end of property to distinguish
// method/function name
// how can I add placeholder/argument in method and then
// call method on object with 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 which print object property and take object as an argument
var printObjectProperty = function(object) {
console.log(object.prop1);
};
// call printObjectProperty with Bar object as an argument
printObjectProperty(Bar); // logs prop1var in console
// call Bar method printObjectPropertyM
Bar.printObjectPropertyM(); // logs prop1val in console
如果我的评论、代码或伪代码有问题,请善待并纠正我。