我正在阅读可以在此链接上找到的打开图层文档,但我对语法不了解。
代码的一部分是这样:
function flickrStyle(feature) {
//where does this feature come from?
var style = new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
stroke: new ol.style.Stroke({
color: 'white',
width: 2
}),
fill: new ol.style.Fill({
color: 'green'
})
})
});
return [style];
}
var flickrLayer = new ol.layer.Vector({
style: flickrStyle //??? where is parameter which needs to be sent? Should this be something like flickrStyle(someParam)
});
您可以看到,源是从flickrstyle函数中提取的,显然需要特征参数,但是我看不到代码中的任何地方,实际上已发送参数。
这是如何工作的?
如果您合理且一致地格式化(通常是这种情况):
function flickrStyle(feature) {
//where does this feature come from?
var style = new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
stroke: new ol.style.Stroke({
color: 'white',
width: 2
}),
fill: new ol.style.Fill({
color: 'green'
})
})
});
return [style];
}
var flickrLayer = new ol.layer.Vector({
style: flickrStyle //??? where is parameter which needs to be sent? Should this be something like flickrStyle(someParam)
});
传递给ol.layer.Vector
的对象中的style: flickrStyle
属性传递函数参考本身,而不是对其进行调用。查看 ol.layer.Vector
文档, ol.layer.Vector
知道 call 如果/必要时,则函数(在feature
参数的参数中传递)。
显然,特定函数不使用 feature
参数(并且可能只是从参数列表中省略了),但是也许作者将其留在那里,因为它确实传递了该参数的值(根据 StyleFunction
docs链接从上面的文档中),可以将功能编辑以稍后使用。
这是同类事物的更简单示例:
// Stand-in for ol.layer.Vector
class Foo {
constructor(options) {
this.style = options.style;
this.counter = 0;
}
addElement() {
const div = document.createElement("div");
++this.counter;
div.innerHTML = "Div #" + this.counter;
if (typeof this.style === "function") {
this.style(div); // <=== This is like ol.layer.Vector's call to the function
}
document.body.appendChild(div);
}
}
// Our style function
function ourStyleFunction(element) {
element.style.color = Math.random() < 0.5 ? "blue" : "green";
element.style.fontWeight = "bold";
}
// Creating an object passing in that function as an option
const f = new Foo({
style: ourStyleFunction
});
// Doing something with it that makes it call the function
f.addElement();
f.addElement();
f.addElement();
f.addElement();
你是对的, feature
在该方法中不使用。
var flickrLayer = new ol.layer.Vector({
style: flickrStyle // this is a function reference, so the Vector class will call it with a given parameter (probably "feature")
});