JavaScript接口实现代码 (Interfaces In JavaScript)_js面向对象

在实际中,我们可以在注释中定义好接口,在实际的代码中予以实现
比如:

复制代码 代码如下:

/*
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 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.
}

这种方法让程序员在写的时候注明实现了哪些接口: this.implementsInterfaces = ['Composite', 'FormItem']; 在调用的时候使用implements方法来判断是否实现了,理论上可行,很有可能写上了实现了'Composite'接口,但是代码里却并没有add方法!因此,我们需要检验实现接口的类是否包含了接口里的方法!所以,接口必须从注释中解放出来:

复制代码 代码如下:

// Interfaces.
var Composite = new Interface('Composite', ['add', 'remove', 'getChild']);
var FormItem = new Interface('FormItem', ['save']);
// CompositeForm class
var CompositeForm = function(id, method, action) { // implements Composite, FormItem
...
};
...
function addForm(formInstance) {
Interface.ensureImplements(formInstance, Composite, FormItem);
// This function will throw an error if a required method is not implemented,
// halting execution of the function.
// All code beneath this line will be executed only if the checks pass.
...
}

定义接口Composite,FormItem,并且CompositeForm实现这两个接口,在使用的时候,用Interface.ensureImplements来检验formInstance是否实现了这两个接口中的所有方法。
来看看Interface的定义:两个参数,第一个参数是接口名称,第二个参数是接口包含的方法数组

复制代码 代码如下:

// 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]);
}
};

为Interface 添加建议接口是否实现的静态方法

复制代码 代码如下:

// Constructor.
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.");
}
}
}
};

时间: 2024-07-29 18:21:16

JavaScript接口实现代码 (Interfaces In JavaScript)_js面向对象的相关文章

JavaScript 核心参考教程 内置对象_js面向对象

这个标准基于 JavaScript (Netscape) 和 JScript (Microsoft).Netscape (Navigator 2.0) 的 Brendan Eich 发明了这门语言,从 1996 年开始,已经出现在所有的 Netscape 和 Microsoft 浏览器中.ECMA-262 的开发始于 1996 年,在 1997 年 7 月,ECMA 会员大会采纳了它的首个版本. 本系列教程旨在向大家分享本人当年学习Javascript的笔记和心得.本系列教程预计分五个部分. 第

JavaScript 继承详解(一)_js面向对象

面向对象与基于对象 几乎每个开发人员都有面向对象语言(比如C++.C#.Java)的开发经验. 在传统面向对象的语言中,有两个非常重要的概念 - 类和实例. 类定义了一类事物公共的行为和方法:而实例则是类的一个具体实现. 我们还知道,面向对象编程有三个重要的概念 - 封装.继承和多态. 但是在JavaScript的世界中,所有的这一切特性似乎都不存在. 因为JavaScript本身不是面向对象的语言,而是基于对象的语言. 这里面就有一些有趣的特性,比如JavaScript中所有事物都是对象, 包

JavaScript 常见对象类创建代码与优缺点分析_js面向对象

在Javascript中构建一个类有好几种方法: 1.Factory 方式 复制代码 代码如下: function createCar(){ var car = new Object(); car.color="b"; car.length=1; car.run=function(){alert("run");} return car; } 定义这么一个函数之后,就可以用: var car1 = createCar(); var car2 = createCar()

javascript Base类 包含基本的方法_js面向对象

复制代码 代码如下: <script type="text/javascript"> function Base(){} //根抽象类 Base.toBase=function(){ //将一个对象转化成Base类的实例的方法 return new Base(); } Base.inherit=function(parent){ //用于继承Base类的实例的方法 var F=function(){} F.prototype=parent; return new F; }

JavaScript 继承详解(三)_js面向对象

注:本章中的jClass的实现参考了Simple JavaScript Inheritance的做法. 首先让我们来回顾一下第一章中介绍的例子: function Person(name) { this.name = name; } Person.prototype = { getName: function() { return this.name; } } function Employee(name, employeeID) { this.name = name; this.employe

JavaScript 继承详解(四)_js面向对象

Classical Inheritance in JavaScript. Crockford是JavaScript开发社区最知名的权威,是JSON.JSLint.JSMin和ADSafe之父,是<JavaScript: The Good Parts>的作者. 现在是Yahoo的资深JavaScript架构师,参与YUI的设计开发. 这里有一篇文章详细介绍了Crockford的生平和著作. 当然Crockford也是我等小辈崇拜的对象. 调用方式 首先让我们看下使用Crockford式继承的调用

JavaScript类和继承 this属性使用说明_js面向对象

this属性表示当前对象,如果在全局作用范围内使用this,则指代当前页面对象window: 如果在函数中使用this,则this指代什么是根据运行时此函数在什么对象上被调用. 我们还可以使用apply和call两个全局方法来改变函数中this的具体指向. 先看一个在全局作用范围内使用this的例子: 复制代码 代码如下: <script type="text/javascript"> console.log(this === window); // true consol

JavaScript 构造函数 面相对象学习必备知识_js面向对象

复制代码 代码如下: function A(x) { this.x = x; } var obj = new A(5); alert(obj.x); 这段代码十分简单,但是我们重要的是看到了一个十分惊讶的结果,obj被我们赋予了一个属性x,就如同我们在C#中使用某个类的实例的时候一样.那么这个属性是怎么样产生的呢? 关键语句:this.x=x.这句话就是进行一个属性的申明与赋值,这里,我们肯定会问到,this是什么?为什么可以使用this.x来进行申明与赋值属性呢? 其实this代表的就是我们刚

实现JavaScript中继承的三种方式_js面向对象

一.原型链继承 在原型链继承方面,JavaScript与java.c#等语言类似,仅允许单父类继承.prototype继承的基本方式如下: 复制代码 代码如下: function Parent(){} function Child(){} Child.prototype = new Parent(); 通过对象Child的prototype属性指向父对象Parent的实例,使Child对象实例能通过原型链访问到父对象构造所定义的属性.方法等. 构造通过原型链链接了父级对象,是否就意味着完成了对象