<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Functional Javascript</title>
<link rel="stylesheet" type="text/css" href="../../css/styles.css"/>
<script type="text/javascript" src="../../lib/d3.js"></script>
</head>
<body>
<script type="text/javascript">
function SimpleWidget(spec) {
var instance = {}; // <-- A
var headline, description; // <-- B
instance.render = function () {
var div = d3.select('body').append("div");
div.append("h3").text(headline); // <-- C
div.attr("class", "box")
.attr("style", "color:" + spec.color) // <-- D
.append("p")
.text(description); // <-- E
return instance; // <-- F
};
instance.headline = function (h) {
if (!arguments.length) return headline; // <-- G
headline = h;
return instance; // <-- H
};
instance.description = function (d) {
if (!arguments.length) return description;
description = d;
return instance;
};
return instance; // <-- I
}
var widget = SimpleWidget({color: "#6495ed"})
.headline("Simple Widget")
.description("This is a simple widget demonstrating functional javascript.");
widget.render();
</script>
</body>
</html>
重点在G标记和H标记
headline在参数不同的情况下,可以分别作为setter和getter
不传参数,从G返回一个子对象headline(父对象的属性),headline是getter
传入参数,从H返回一个父对象instance(设置了属性的),headline是setter
在返回的instance上可以立刻执行另一个函数,此即为链式调用.
网友评论