JavaScript 中的接口有必要吗?

发布于 2024-08-05 05:10:20 字数 354 浏览 4 评论 0原文

我想这可以适用于任何动态语言,但我使用的是 JavaScript。我们遇到的情况是,我们正在 JavaScript 中编写几个控件,这些控件需要公开 Send() 函数,然后由托管 JavaScript 的页面调用该函数。我们有一个定义了 Send 函数的对象数组,因此我们迭代该集合并对每个对象调用 Send()。

在面向对象语言中,如果您想做类似的事情,您将拥有一个 IControl 接口,该接口具有必须由每个控件实现的 Send() 函数,然后您将拥有一个可迭代的 IControl 实现的集合通过并调用发送方法。

我的问题是,由于 JavaScript 是一种动态语言,是否需要定义控件应继承的接口,或者仅调用控件上公开的 Send() 函数就足够了?

I suppose this could apply to any dynamic language, but the one I'm using is JavaScript. We have a situation where we're writing a couple of controls in JavaScript that need to expose a Send() function which is then called by the page that hosts the JavaScript. We have an array of objects that have this Send function defined so we iterate through the collection and call Send() on each of the objects.

In an OO language, if you wanted to do something similar, you'd have an IControl interface that has a Send() function that must be implemented by each control and then you'd have a collection of IControl implementations that you'd iterate through and call the send method on.

My question is, with JavaScript being a dynamic language, is there any need to define an interface that the controls should inherit from, or is it good enough to just call the Send() function exposed on the controls?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

谈场末日恋爱 2024-08-12 05:10:20

动态语言通常鼓励鸭子类型,其中对象的方法决定了应该如何使用它,而不是显式契约(例如接口)。

Dynamic languages often encourage Duck Typing, in which methods of the object dictate how it should be used rather than an explicit contract (such as an interface).

Spring初心 2024-08-12 05:10:20

PHP 也是如此;你真的不需要界面。但它们的存在是为了建筑的需要。在 PHP 中,您可以为有用的函数指定类型提示。

其次,接口就是契约。这是一个正式的契约,来自该接口的所有对象都具有这些功能。最好确保您的类满足这些要求,而不是记住:“嗯,这个类有 isEnabled(),但另一个是 checkIfEnabled()”。接口可帮助您实现标准化。其他处理派生对象的人不必检查名称是 isEnabled 还是 checkIfEnabled(最好让解释器捕获这些问题)。

This is the same for PHP; you don't really need interfaces. But they exist for architectural needs. In PHP, you can specify type hints for functions which can be useful.

Second, an interface is a contract. It's a formal contract that all objects from this interface have those functions. Better to ensure that your classes meet those requirements than to remember: "mm, this class has isEnabled() but the other one is checkIfEnabled()". Interfaces help you to standardise. Others working on the derived object don't have to check whether the name is isEnabled or checkIfEnabled (better to let the interpreter catch those problems).

且行且努力 2024-08-12 05:10:20

由于您可以使用动态语言调用任何对象上的任何方法,因此我不确定接口如何以任何真正有用的方式发挥作用。没有强制执行的契约,因为一切都是在调用时确定的——对象甚至可以在其生命周期中改变它是否符合“契约”,因为在整个运行时添加和删除方法。如果对象不履行合同,则调用将失败;如果对象未实现成员,则调用将失败 - 对于大多数实际用途,这两种情况都是相同的。

Since you can call any method on any object in a dynamic language, I'm not sure how interfaces would come into play in any truly useful way. There are no contracts to enforce because everything is determined at invocation time - an object could even change whether it conforms to a "contract" through its life as methods are added and removed throughout runtime. The call will fail if the object doesn't fulfill a contract or it will fail if it doesn't implement a member - either case is the same for most practical purposes.

汹涌人海 2024-08-12 05:10:20

我们在下面的页面中看到了一个很好的实现,这是我们的(它的简短版本)

var Interface = function (methods) {
    var self = this;
    self.methods = [];

    for (var i = 0, len = methods.length; i < len; i++) {
        self.methods.push(methods[i]);
    }

    this.implementedBy = function (object) {

        for (var j = 0, methodsLen = self.methods.length; j < methodsLen; j++) {
            var method = self.methods[j];
            if (!object[method] || typeof object[method] !== 'function') {
                return false;
            }
        }
        return true;
    }
};

//Call
var IWorkflow = new Interface(['start', 'getSteps', 'end']);
if (IWorkflow.implementedBy(currentWorkFlow)) {
    currentWorkFlow.start(model);
}

整个示例位于:
http://www.javascriptbank.com/how-implement-interfaces-in -javascript.html

We saw a nice implementation in the page below, this is ours (short version of it)

var Interface = function (methods) {
    var self = this;
    self.methods = [];

    for (var i = 0, len = methods.length; i < len; i++) {
        self.methods.push(methods[i]);
    }

    this.implementedBy = function (object) {

        for (var j = 0, methodsLen = self.methods.length; j < methodsLen; j++) {
            var method = self.methods[j];
            if (!object[method] || typeof object[method] !== 'function') {
                return false;
            }
        }
        return true;
    }
};

//Call
var IWorkflow = new Interface(['start', 'getSteps', 'end']);
if (IWorkflow.implementedBy(currentWorkFlow)) {
    currentWorkFlow.start(model);
}

The whole example is at:
http://www.javascriptbank.com/how-implement-interfaces-in-javascript.html

原野 2024-08-12 05:10:20

bob.js 提供了接口的另一种替代方案:

1。检查接口是否实现:

var iFace = { say: function () { }, write: function () { } };  
var obj1 = { say: function() { }, write: function () { }, read: function () { } }; 
var obj2 = { say: function () { }, read: function () { } }; 
console.log('1: ' + bob.obj.canExtractInterface(obj1, iFace)); 
console.log('2: ' + bob.obj.canExtractInterface(obj2, iFace)); 
// Output: 
// 1: true 
// 2: false 

2.从对象中提取接口并仍然正确执行功能:

var obj = {  
    msgCount: 0, 
    say: function (msg) { console.log(++this.msgCount + ': ' + msg); }, 
    sum: function (a, b) { console.log(a + b); } 
}; 
var iFace = { say: function () { } }; 
obj = bob.obj.extractInterface(obj, iFace); 
obj.say('Hello!'); 
obj.say('How is your day?'); 
obj.say('Good bye!'); 
// Output: 
// 1: Hello! 
// 2: How is your day? 
// 3: Good bye! 

Another alternative to the interfaces is offered by bob.js:

1. Check if the interface is implemented:

var iFace = { say: function () { }, write: function () { } };  
var obj1 = { say: function() { }, write: function () { }, read: function () { } }; 
var obj2 = { say: function () { }, read: function () { } }; 
console.log('1: ' + bob.obj.canExtractInterface(obj1, iFace)); 
console.log('2: ' + bob.obj.canExtractInterface(obj2, iFace)); 
// Output: 
// 1: true 
// 2: false 

2. Extract interface from the object and still execute the functions properly:

var obj = {  
    msgCount: 0, 
    say: function (msg) { console.log(++this.msgCount + ': ' + msg); }, 
    sum: function (a, b) { console.log(a + b); } 
}; 
var iFace = { say: function () { } }; 
obj = bob.obj.extractInterface(obj, iFace); 
obj.say('Hello!'); 
obj.say('How is your day?'); 
obj.say('Good bye!'); 
// Output: 
// 1: Hello! 
// 2: How is your day? 
// 3: Good bye! 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文