您的位置:首页 > Web前端 > JavaScript

javascript的接口定义之鸭式辨型

2016-02-20 21:38 761 查看
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var Interface = function(name, methods){
if(arguments.length != 2){
throw new Error('Interface constructor called with ' + arguments.length
+ 'arguments, but expected exactly 2.');
}

this.name = name;
this.methods = [];
for(var i=0,len = methods.length; i<len; i++){
if(typeof methods[i] != 'string'){
throw new Error('Interface constructor expected method names to be '
+ 'passed in as a string.');
}
this.methods.push(methods[i]);
}
};

Interface.ensureImplements = function(object){
if(arguments.length < 2){
throw new Error("Function Interface.ensureImplements called with " + arguments.length
+ " arguments, but expected at least 2.");
}

for(var i=1,len = arguments.length; i < len; i++){
var interface = arguments[i];
if(interface.constructor != Interface){
throw new Error("Function Interface.ensureImplements expects arguments "
+ "two and above to be instances of Interface.");
}

for(var j=0,methodslen = interface.methods.length; j < methodslen; j++){
var method = interface.methods[j];
if(!object[method] || typeof object[method] !== 'function'){
throw new Error("Function Interface.ensureImplements: object " +
"does not implements the " + interface.name + " interface.Method " +
method + " was not found.");
}
}
}
};

// 定义接口
var DynamicMap = new Interface('DynamicMap', ['centerOnPoint', 'zoom', 'draw']);

function displayRoute(mapInstance){
// 接口实现检查
Interface.ensureImplements(mapInstance, DynamicMap);

mapInstance.centerOnPoint(24, 13);
mapInstance.zoom(5);
mapInstance.draw();
}

// 对象
function Foo(){
}

Foo.prototype = {
centerOnPoint : function(x, y){
document.writeln('<br />centerOnPoint: ' + x + ', ' + y);
},
zoom : function(level){
document.writeln('<br />zoom: ' + level);
},
draw : function(){
document.writeln('<br />draw');
}
};

var foo = new Foo();
displayRoute(foo);

</script>
</head>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: