Trong các ngôn ngữ lập trình hướng đối tượng, Interface có tác dụng định nghĩa một tập hợp các phương thức mà lớp kế thừa cần phải nạp và định nghĩa lại để sử dụng. Tuy nhiên, trong bản thân ngôn ngữ lập trình JavaScript không thực sự có đối tượng lớp; vì vậy bài viết JavaScript này hướng dẫn bạn cách thức giả lập một Interface trong ngôn ngữ JavaScript.
- Demo
- Phóng to
- Tải lại
- Cửa sổ mới
Miễn phí web hosting 1 năm đầu tại iPage
Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?
Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.
Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Updated: April 17th, 2013
In Object-Oriented languages an interface defines a set of methods which a Class must include in order to implement the interface (otherwise, if the Class is missing the required methods, the code will fail and the interface will throw an error).
Interfaces are useful for making sure developers use the correct implementation of an API.
In JavaScript there are no true 'classic' Object-Oriented features, but through clever usage of the language you can emulate an Interface for use with a JavaScript API.
First thing you want to do is include the following JavaScript file (Interface.js
) into your HTML:
/* * Constructor that creates a new Interface object for checking a function implements the required methods. * @param objectName | String | the instance name of the Interface * @param methods | Array | methods that should be implemented by the relevant function */ var Interface = function (objectName, methods) { // Check that the right amount of arguments are provided if (arguments.length != 2) { throw new Error ("Interface constructor called with " + arguments.length + "arguments, but expected exactly 2."); } // Create the public properties this.name = objectName; this.methods = []; // Loop through provided arguments and add them to the 'methods' array for (var i = 0, len = methods.length; i < len; i++) { // Check the method name provided is written as a String if (typeof methods[i] !== 'string') { throw new Error ("Interface constructor expects method names to be " + "passed in as a string."); } // If all is as required then add the provided method name to the method array this.methods.push(methods[i]); } }; /* * Adds a static method to the 'Interface' constructor * @param object | Object Literal | an object literal containing methods that should be implemented */ Interface.ensureImplements = function (object) { // Check that the right amount of arguments are provided if (arguments.length < 2) { throw new Error ("Interface.ensureImplements was called with " + arguments.length + "arguments, but expected at least 2."); } // Loop through provided arguments (notice the loop starts at the second argument) // We start with the second argument on purpose so we miss the data object (whose methods we are checking exist) for (var i = 1, len = arguments.length; i < len; i++) { // Check the object provided as an argument is an instance of the 'Interface' class var interface = arguments[i]; if (interface.constructor !== Interface) { throw new Error ("Interface.ensureImplements expects the second argument to be an instance of the 'Interface' constructor."); } // Otherwise if the provided argument IS an instance of the Interface class then // loop through provided arguments (object) and check they implement the required methods for (var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) { var method = interface.methods[j]; // Check method name exists and that it is a function (e.g. test[getTheDate]) // if false is returned from either check then throw an error if (!object[method] || typeof object[method] !== 'function') { throw new Error ("This Class does not implement the '" + interface.name + "' interface correctly. The method '" + method + "' was not found."); } } } };
Next, in the HTML file we have an inline script that creates a new Interface instance and then passes it the methods we are expecting. The user of the API would need to implement an object literal of all the methods the interface requires (note the following code could be in a separate SCRIPT file as long as it is run after the above script):
// We pass into the Interface the name of the current Interface instance, // followed by an Array of the methods we are expecting to find var test = new Interface('test', ['details', 'age']); var properties = { name: "Mark McDonnell", actions: { details: function() { return "I am " + this.age() + " years old."; }, age: (function(birthdate) { var dob = new Date(birthdate), today = new Date(), ms = today.valueOf() - dob.valueOf(), minutes = ms / 1000 / 60, hours = minutes / 60, days = hours / 24, years = days / 365, age = Math.floor(years) return function() { return age; }; })("1981 08 30") } }; // Create a Person constructor that will implement the above properties/methods function Person(config) { // Pass in the methods we are expecting, // followed by the name of the Interface instance that we're checking against Interface.ensureImplements(config.actions, test); this.name = config.name; this.methods = config.actions; } // Create a new instance of the Person constructor... var me = new Person(properties); // ...and make sure the methods are working alert(me.methods.age()); alert(me.method.details());
- Lượt gửi (0)
- Mới
Save up to 630$ when buy new iPhone 15
GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project
https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools
chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language
Dall-E-OpenAI.com
Generate creative images automatically with AI
AIVideo-App.com
Render creative video automatically with AI
Test Phản hồi