JavaScript“.method”返回undefined

时间:2015-04-08 15:26:20

标签: javascript inheritance

以下脚本:

    <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>
在控制台中我可以看到:&#34;未定义的不是函数&#34;指的是:

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

我错过了什么吗?

2 个答案:

答案 0 :(得分:5)

功能没有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的实例(并声明变量):

&#13;
&#13;
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);
&#13;
<!-- 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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您希望将方法添加到对象的原型中。

来自MDN

  

JavaScript中的所有对象都来自Object;所有对象都从Object.prototype继承方法和属性。因此,当您运行new Parenizor(0)时,您将创建一个Parenizor的新实例,该实例将具有在其原型上定义的所有可用功能。

所以你需要扩展你的函数的原型

Parenizor.prototype.setValue = function (value){
    this.value = value;
    return this;
};
相关问题