㈠ javascript如何实现接口
在javascript中并没有原生的创建或者实现接口的方式,或者判定一个类型是否实现了某个接口,我们只能利用js的灵活性的特点,模拟接口。
在javascript中实现接口有三种方式:注释描述、属性验证、鸭子模型。
note:因为我看的是英文书,翻译水平有限,不知道有些词汇如何翻译,大家只能领会精神了。
1. 注释描述 (Describing Interfaces with Comments)
例子:
复制代码 代码如下:
/*
interface Composite {
function add(child);
function remove(child);
function getChild(index);
}
interface FormItem {
function save();
}
*/
var CompositeForm = function(id, method, action) { // implements Composite, FormItem
...
};
//Implement the Composite interface.
CompositeForm.prototype.add = function(child) {
...
};
CompositeForm.prototype.remove = function(child) {
...
};
CompositeForm.prototype.getChild = function(index) {
...
};
// Implement the FormItem interface.
CompositeForm.prototype.save = function() {
...
};
模拟其他面向对象语言,使用interface 和 implements关键字,但是需要将他们注释起来,这样就不会有语法错误。
这样做的目的,只是为了告诉其他编程人员,这些类需要实现什么方法,需要在编程的时候加以注意。但是没有提供一种验证方式,这些类是否正确实现了这些接口中的方法,这种方式就是一种文档化的作法。
2. 属性验证(Emulating Interfaces with Attribute Checking)
例子:
复制代码 代码如下:
/* interface
Composite {
function add(child);
function remove(child);
function getChild(index);
}
interface FormItem {
function save();
}
*/
var CompositeForm = function(id, method, action) {
this.implementsInterfaces = ['Composite', 'FormItem'];
...
};
...
function addForm(formInstance) {
if(!implements(formInstance, 'Composite', 'FormItem')) {
throw new Error("Object does not implement a required interface.");
}
...
}
// The implements function, which checks to see if an object declares that it
// implements the required interfaces.
function implements(object) {
for(var i = 1; i < arguments.length; i++) {
// Looping through all arguments
// after the first one.
var interfaceName = arguments[i];
var interfaceFound = false;
for(var j = 0; j < object.implementsInterfaces.length; j++) {
if(object.implementsInterfaces[j] == interfaceName) {
interfaceFound = true;
break;
}
}
if(!interfaceFound) {
return false;
// An interface was not found.
}
}
return true;
// All interfaces were found.
}
这种方式比第一种方式有所改进,接口的定义仍然以注释的方式实现,但是添加了验证方法,判断一个类型是否实现了某个接口。
3.鸭子类型(Emulating Interfaces with Duck Typing)
复制代码 代码如下:
// Interfaces.
var Composite = new Interface('Composite', ['add', 'remove', 'getChild']);
var FormItem = new Interface('FormItem', ['save']);
// CompositeForm class
var CompositeForm = function(id, method, action) {
...
};
...
function addForm(formInstance) {
ensureImplements(formInstance, Composite, FormItem);
// This function will throw an error if a required method is not implemented.
...
}
// Constructor.
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 expects method names to be "
+ "passed in as a string.");
}
this.methods.push(methods[i]);
}
};
// Static class method.
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 implement the " + interface.name + " interface. Method " + method + " was not found.");
}
}
}
};
何时使用接口?
一直使用严格的类型验证并不适合,因为大多数javascript程序员已经在没有接口和接口验证的情况下编程多年。当你用设计模式开始设计一个很复杂的系统的时候,使用接口更有益处。看起来使用接口好像限制了javascript的灵活性,但实际上他让你的代码变得更加的松耦合。他使你的代码变得更加灵活,你可以传送任何类型的变量,并且保证他有你想要的方法。有很多场景接口非常适合使用。
在一个大型系统里,很多程序员一起参与开发项目,接口就变得非常必要了。程序员经常要访问一个还没有实现的api,或者为其他程序员提供别人依赖的一个方法存根,在这种情况下,接口变得相当的有价值。他们可以文档化api,并作为编程的契约。当存根被实现的api替换的时候你能立即知道,如果在开发过程中api有所变动,他能被另一个实现该接口的方法无缝替换。
如何使用接口?
首先要解决的问题是,在你的代码中是否适合使用接口。如果是小项目,使用接口会增加代码的复杂度。所以你要确定使用接口的情况下,是否是益处大于弊端。如果要使用接口,下面有几条建议:
1.引用Interface 类到你的页面文件。interface的源文件你可以再如下站点找到: http://jsdesignpatterns.com/.
2.检查你的代码,确定哪些方法需要抽象到接口里面。
3.创建接口对象,没个接口对象里面包含一组相关的方法。
4.移除所有构造器验证,我们将使用第三种接口实现方式,也就是鸭子类型。
5.用Interface.ensureImplements替代构造器验证。
您可能感兴趣的文章:
小议javascript 设计模式 推荐
JavaScript 设计模式之组合模式解析
javascript 设计模式之单体模式 面向对象学习基础
JavaScript 设计模式 安全沙箱模式
JavaScript设计模式之观察者模式(发布者-订阅者模式)
JavaScript设计模式之原型模式(Object.create与prototype)介绍
JavaScript设计模式之工厂方法模式介绍
javascript设计模式之中介者模式Mediator
学习JavaScript设计模式之责任链模式
㈡ 纯js调用webservice接口怎么调用
纯js调用webservice接口举例:
1、HelloWorld.htm (calls Hello World method):
<html>
<head>
<title>Hello World</title>
<script language="JavaScript">
var iCallID;
function InitializeService(){
service.useService(http://localhost:1394/MyWebService.asmx?wsdl,
"HelloWorldService");
service.HelloWorldService.callService("HelloWorld");
}
function ShowResult(){
alert(event.result.value);
}
</script>
</head>
<body onload="InitializeService()" id="service"
style="behavior:url(webservice.htc)" onresult="ShowResult()"> </body>
</html>
2、GetAge.htm (calls GetAge method, takes 3 parameters):
<html>
<head>
<title>UseSwap</title>
<script language="JavaScript">
function InitializeService(){
service.useService(http://localhost:1394/MyWebService.asmx?wsdl,
"GetAgeService");
}
var StrYear, StrMonth, StrDay;
function GetAge(){
StrYear = document.DemoForm.StringYear.value;
StrMonth = document.DemoForm.StringMonth.value;
StrDay = document.DemoForm.StringDay.value;
service.GetAgeService.callService("GetAge", StrYear, StrMonth, StrDay);
}
function ShowResult(){
alert(event.result.value);
}
</script>
</head>
<body onload="InitializeService()" id="service"
style="behavior:url(webservice.htc)" onresult="ShowResult()">
<form name="DemoForm">
Year : <input type="text" name="StringYear"/>
Month : <input type="text" name="StringMonth"/>
Day : <input type="text" name="StringDay"/>
<button onclick="GetAge()">Get Age</button>
</form>
</body>
</html>
3、GetDateTime.htm (returns cached value):
<html>
<head>
<meta http-equiv="refresh" content="2" />
<title>Get Date Time</title>
<script language="JavaScript">
var iCallID;
function InitializeService(){
service.useService(http://localhost:1394/MyWebService.asmx?wsdl,
"GetDateTimeService");
service.GetDateTimeService.callService("GetDateTime");
}
function ShowResult(){
alert(event.result.value);
}
</script>
</head>
<body onload="InitializeService()" id="service"
style="behavior:url(webservice.htc)" onresult="ShowResult()">
</body>
</html>
㈢ AngularJS如何调用外部接口
第一步:准备工作
将AngularJS脚本添加到该文档的当中:
在此之后,可以在将这套CCS样式添加到行内或者独立的文件当中:
*{
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
font-family:sans-serif;
}
body,html{margin:0;}
p{margin:0;}
input{width:100%;}
pre{
white-space:pre-wrap;
white-space:-moz-pre-wrap;
white-space:-pre-wrap;
white-space:-o-pre-wrap;
word-wrap:break-word;
}
div.repo{
border-bottom:1pxsolid;
cursor:pointer;
}
#search,#repo,#user{float:left;}
#search{width:20%;}
#repo{width:60%;}
#user{width:20%;}
如大家所见,其中不存在任何多余的内容、只保留最基础的布局方案——将搜索栏置于右侧、库信息位于中央、用户库同样置于右侧。我们还需要将对应代码行打包至标签当中,此后我们还要利用它显示README文件内容——因为这些内容通常来自GitHub Flavored Markdown、而且其中一部分代码行与用户库列表存在重叠。
当然,大家可以向其中添加更多样式以提升成果的视觉效果——但请注意,本教程中的截图都采取最基本的外观设计。
大家可以未来需要编写的JavaScript代码置于本文档的当中或者为其建立独立文件,但独立文件仍然需要处于AngularJS脚本之下。
第二步:模块
现在我们可以为自己的应用程序创建一个模块:
varapp=angular.mole('githubsearch',[]);
接下来利用ngApp指令将其添加到标签当中:
第三步:控制器
我们还需要为自己的应用程序准备一套控制器。为了简化创建流程,我们将只为应用准备一套控制器,这样我们就不必考虑如何在不同控制器之间进行信息传递了:
app.controller('SearchController',functionSearchController($scope){
});
第四步:基础服务
我们需要对自己的GitHub服务进行定义:
app.factory('GitHub',functionGitHub($http){
return{
};
});
我们将使用app.factory()方法,这样就能保证返回对象附带几个以后将会用到的方法。我们将使用$http服务从GitHub的API中获取数据。
第五步:搜索库
我们服务中的第一项方法负责利用GitHub API对库进行搜索。使用服务非常简单(这项函数能够进入由制造函数返回的对象):
searchRepos:functionsearchRepos(query,callback){
$http.get('https://api.github.com/search/repositories',{params:{q:query}})
.success(function(data){
callback(null,data);
})
.error(function(e){
callback(e);
});
}
$http.get()方法是执行GET请求的一种捷径。第一条参数是我们希望访问的URL。第二条参数则代表一个具备选项的对象。这里我们只需要params对象——它是一个查询参数散列,将被添加到该请求当中(其中q参数属于搜索字符串,大家可以点击此处了解更多相关信息)。
$http.get()会返回一项承诺。我们可以将监听器附加在success()与error()上,并且据此调用回调函数。
第六步:搜索栏
为了使用我们在之前几步中定义完成的函数,我们需要在自己的HTML当中添加搜索栏。
㈣ 怎么用js调用java的接口
http://blog.csdn.net/feifei454498130/article/details/6524183 http://blog.csdn.net/kingsollyu/article/details/6656865
参考这两个 webSettings.setJavaScriptEnabled(true); 是启用js,mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo"); 是定义个对象demo,js中调用demo对象就可以调用刚刚定义的java方法 了。这两个是关键
㈤ js怎么调用地图api接口简书
首先去申请一个API key,获取API key后在页面调用
申请地址:http://lbsyun..com/apiconsole/key?application=key
<script src="http://api.map..com/api?v=2.0&ak=8cprupV34TG3GIxu6CnRE5Ua&service=true" type="text/javascript"></script>
调用api的方法函数
var map = null;
$(function(){
map = new BMap.Map("map");
var point = new BMap.Point(x坐标,y坐标);
map.centerAndZoom(point, 15);
//放大控件
map.addControl(new BMap.NavigationControl());
map.enableScrollWheelZoom();
dingwei("地点标题","地址","电话",x坐标,y坐标);
map.setCurrentCity("广州");
㈥ 微信接口 可以在js中直接调用吗
1.引入JS文件
在需要调用JS接口的页面引入如下JS文件
备注:支持使用 AMD/CMD 标准模块内加载方法加载
2.注入配置config接口
所有容需要使用JSSDK的页面必须先注入配置信息,否则将无法调用(同一个url仅需调用一次,对于变化url的SPA的web app可在每次url变化时进行调用)。
㈦ JS怎么调用API接口
需要准备的材料抄分别是:电脑、html编辑器、浏览器。
1、首先,打开html编辑器,新建html文件,例如:index.html,引入jquery使用。