繁体   English   中英

如何在另一个js文件中实例化一个javascript类?

[英]How to instantiate a javascript class in another js file?

假设我在 file1.js 中定义了一个类

function Customer(){
    this.name="Jhon";
    this.getName=function(){
        return this.name;
    };
};

现在,如果我想在 file2.js 中创建一个 Customer 对象

var customer=new Customer();
var name=customer.getName();

我收到异常: Customer is undefined, not a constructor.

但是当我在 file2.js 中创建一个客户对象并将其传递给 file1.js 然后它的工作。

file1.js

    function Customer(){
        this.name="Jhon";
        this.getName=function(){
            return this.name;
        }
    }
    function customer(){
        return new Customer();
    }

file2.js

    var customer=customer();
    var name=customer.getName();

但我想使用 new Customer() 在 file1.js 中创建一个客户对象。 我怎样才能做到这一点?

这取决于您运行的环境。在 Web 浏览器中,您只需要确保file1.jsfile2.js之前file2.js

<script src="file1.js"></script>
<script src="file2.js"></script>

在 node.js 中,推荐的方法是让 file1 成为一个模块,然后你可以使用require函数加载它:

require('path/to/file1.js');

也可以使用require.js库在 HTML 中使用节点的模块样式。

// Create Customer class as follows:
export default class Customer {
   getName() {
     return 'stackoverflow';
   }
}

// Import the class 
// no need for .js extension in path cos it gets inferred automatically
import Customer from './path/to/Customer'; 
// OR
const Customer = require('./path/to/Customer') 

// Use the class
var customer = new Customer();
var name = customer.getName();

您可以导出您的方法以从其他文件访问,如下所示:

文件1.js

var name = "Jhon";
exports.getName = function() {
  return name;
}

文件2.js

var instance = require('./file1.js');
var name = instance.getName();

在 file2 中运行代码之前,请确保已加载 dom... 如果您使用的是 jQuery:

$(function(){
  var customer=customer();
  var name=customer.getName();
});

那么无论文件的顺序如何,代码都不会运行,直到所有文件都加载完毕。

如果你在 HTML 中使用 javascript,你应该在你的 html 中包含file1.jsfile2.js

<script src="path_to/file1.js"></script>
<script src="path_to/file2.js"></script>

注意, file1应该在file2之前出现。

使其工作的可能建议:

一些修改(你忘了在语句中包含分号this.getName=function(){...}应该是this.getName=function(){...};

function Customer(){
this.name="Jhon";
this.getName=function(){
return this.name;
};
}

(这可能是问题之一。)

确保以正确的顺序链接 JS 文件

<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>

这跟它的价值undefined ,因为它是一个构造function ,而不是一个classconstructor 为了使用它,您需要使用Customer()customer()

首先,你需要file2.js之前加载 file1.js,就像 slebetman 说的:

<script defer src="file1.js" type="module"></script>
<script defer src="file2.js" type="module"></script>

然后,您可以按如下方式更改 file1.js:

export default class Customer(){
    constructor(){
        this.name="Jhon";
        this.getName=function(){
            return this.name;
        };
    }
}

而 file2.js 如下:

import { Customer } from "./file1";
var customer=new Customer();

如果我错了,请纠正我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM