【问题标题】:Declaring JavaScript prototype for require.js为 require.js 声明 JavaScript 原型
【发布时间】:2014-06-12 17:56:51
【问题描述】:

我对 JavaScript OOP 和 require.js 都很陌生

我正在学习使用 require.js 来提高应用程序的可扩展性,我尝试在 Google 上搜索文章,但由于我的 JavaScript 背景不佳,我并没有真正理解。

我想出了这个编码。

employee.js

define([], function() {
      function Employee(empName) {
         return {
            _empName: empName,
             getEmployeeName: function() {
                return _empName;
             }
         }
     }
});

customer.js

define([], function() {
    function Customer(customerName) {
        this._customerName = customerName;

        this.getCustomerName = function() {
            return this._customerName;
        }
    }

    return(Customer);
});

我已经为 Employee 和 Customer 原型尝试了 2 种不同风格的编码。

main.js

require(['customer', 'employee'], function(Customer, Employee) {
    c = new Customer('Boy');
    console.log('Customer name is ' + c.getCustomerName());

    e = new Employee('Mike');
    console.log('Employee name is ' + e.getEmployeeName());
});

这是我得到的结果。

我的问题是,customer.js 中的编码只是声明原型以与 require.js 一起使用的方式吗?

我的理解是 require.js 总是并且只将依赖项注入为 class(不是实例)对吗?

通过回答这 2 个简单的问题来帮助我将帮助我进入下一步的学习,任何建议的文章都将非常感激,(我真的不知道要搜索哪些特定主题)。

谢谢

【问题讨论】:

    标签: javascript requirejs js-amd


    【解决方案1】:

    我的问题是 customer.js 中的编码只是声明原型以与 require.js 一起使用的方式吗?

    没有。使用原型与使用 require.js 无关。

    我的理解是 require.js 总是并且只将依赖项作为类(而不是实例)注入,对吗?

    没有。它会注入您从模块定义返回的任何内容。如果是employee.js,那没什么; Employee 最终成为 undefined


    所以修正你的员工代码:

    define([], function() {
        function makeEmployee(empName) { // it's not a constructor - don't capitalize
                                         // it shouldn't be invoked with `new` either
            return {
                _empName: empName,
                getEmployeeName: function() {
                    return this._empName; // it's a property, not a variable
                }
            }
        }
        return makeEmployee; // return the function to become the module!
    });
    

    【讨论】:

    • 为了与require.js一起使用,我应该使用你的编码方式而不是我的customer.js,对吧?
    • 不,您的 customer.js 很好。你可以将getCustomerName 放在原型上,但这与require.js 无关。
    • 这就是你的意思Customer.prototype.getCustomerName = function() {} 吗?
    猜你喜欢
    • 1970-01-01
    • 2011-06-28
    • 2013-09-15
    • 2011-08-07
    • 2011-07-16
    • 2012-07-15
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多