JavaScript“.method”returns未定义

JavaScript ".method" returns undefined

以下脚本:

    <script>
        function Parenizor (value){
            this.setValue(value);
        }

        Parenizor.method('setValue', function (value){
            this.value = value;
            return this;
        });

        Parenizor.method('getValue', function (){
            return this.value;
        });

        Parenizor.method('toString', function(){
            return '(' + this.getValue() + ')';
        });

        myParenizor = new Parenizor(0);
        myString = myParenizor.toString();

        console.log(myParenizor, myString);
    </script>

在控制台中我可以看到:"undefined is not a function"指的是:

Parenizor.method('setValue', function (value){

我是不是漏掉了什么?

函数没有 method 属性,这就是您得到 undefined 的原因。您可能正在考虑对 Douglas Crockford 喜欢使用的函数进行扩展,如下所示:

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

但这不是 JavaScript 的一部分,这是 Crockford 的事情。你必须在你的代码中包含该代码并在你做你的事情之前执行它才能使用它。

如您所见,它几乎什么都不做;它是 最小的 语法糖。例如,要在没有它的情况下创建 setValue 方法,您可以这样做:

Parenizor.prototype.setValue = function(value) {
  this.value = value;
  return this;
};

如果您不想使用 Crockford 的 method 功能,请改用它。


旁注:您正在成为 The Horror of Implicit Globals 的牺牲品;您需要声明 myParenizormyString 变量。


在使用之前定义 Crockford method 的实例(并声明变量):

Function.prototype.method = function(name, func) {
  this.prototype[name] = func;
  return this;
};

function Parenizor(value) {
  this.setValue(value);
}

Parenizor.method('setValue', function(value) {
  this.value = value;
  return this;
});

Parenizor.method('getValue', function() {
  return this.value;
});

Parenizor.method('toString', function() {
  return '(' + this.getValue() + ')';
});

var myParenizor = new Parenizor(0);
var myString = myParenizor.toString();

snippet.log(JSON.stringify(myParenizor));
snippet.log(myString);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

您想将方法添加到对象的原型

来自MDN

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype. So when you run new Parenizor(0) you will create a new instance of Parenizor which will have all the functions available that where defined on its prototype.

因此您需要扩展函数的原型

Parenizor.prototype.setValue = function (value){
    this.value = value;
    return this;
};