簡體   English   中英

如何創建可重復使用的JavaScript組件

[英]How do I create a reusable JavaScript component

我正在嘗試創建一個可在任何Web應用程序中重用的JavaScript組件(僅允許使用純js)。 一個網頁上一次可以存在多個實例。

客戶端HTML

<head runat="server">
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" />
    <script src="MyComponent.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            MyComponent.init();
        };
    </script>
</head>

MyComponent.js

var MyComponent = {};

(function () {
    var ns = MyComponent;
    ns.init = function () { alert('test'); }
}());

我將如何實例化上面的組件?

這是要點:

function MyComponent() {
  //constructor
}

MyComponent.prototype.doStuff = function() {
  //method
}

MyComponent.doSomething = function() {
  //static method
}

這就是您將如何使用它

var component = new MyComponent();
component.doStuff();

MyComponent.doSomething();

我認為您正在尋找的是構造函數模式 請參閱本頁上的說明和Car示例。

文章摘錄:

function Car( model, year, miles ) {
  this.model = model;
  this.year = year;
  this.miles = miles;
  this.toString = function () {
    return this.model + " has done " + this.miles + " miles";
  };
}
// Usage:
// We can create new instances of the car
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM