对象的调用方法或作为函数参数传递对象有什么区别,因此我如何在方法调用中传递参数?简单地将占位符作为参数并没有产生预期的效果。我是否必须通过所有属性名称(而不是值)进行迭代,然后将给定的参数(作为属性名称)与对象中的属性名称进行比较?
这里有大量评论的代码,因为我很好奇究竟发生了什么。
// 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
如果我的评论,代码或伪代码有问题,请善待并纠正我。
答案 0 :(得分:1)
您应该使用[]
表示法来按名称访问对象的属性。
在构造函数中创建一个方法:
function Foo(prop1val, prop2val) {
this.prop1 = prop1val;
this.prop2 = prop2val;
this.PrintProperty = function (name) {
if (this.hasOwnProperty(name)) {
console.log(this[name]);
}
}
}
现在打电话给:
var bar = new Foo("prop1val", "prop2val");
bar.PrintProperty("prop1");