導航:首頁 > 編程語言 > js定義介面

js定義介面

發布時間:2023-07-06 15:35:56

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使用。

閱讀全文

與js定義介面相關的資料

熱點內容
5g網路什麼時候普及河北邢台 瀏覽:709
編程和運營哪個更適合創業 瀏覽:893
尤里x怎麼升級 瀏覽:399
做業務績效考核需要哪些數據 瀏覽:433
dnf85版本劍魔刷圖加點 瀏覽:407
手機硬碟測試架可以讀取哪些數據 瀏覽:704
ug前後處理結算結果找不到文件 瀏覽:769
網頁框架拆分代碼 瀏覽:382
未來十年網路安全有什麼影響 瀏覽:362
win10更新後進不了劍靈 瀏覽:243
iphone471激活出錯 瀏覽:648
怎麼把文件拷到u盤 瀏覽:620
中伊簽署文件視頻 瀏覽:661
電信光寬頻網路不穩定 瀏覽:504
網路崗軟路由 瀏覽:995
黑莓z10在哪裡下載app 瀏覽:310
net批量下載文件 瀏覽:696
怎麼把蘋果一體機文件拷貝 瀏覽:117
sql文件怎麼寫 瀏覽:9
帝豪ec718導航升級 瀏覽:257

友情鏈接