search

Home  >  Q&A  >  body text

javascript Uncaught TypeError: undefined is not a function

    if (typeof Function.prototype.method !== 'function') {
        Function.prototype.method = function(name,implementation){
            console.log(name);
            Function.prototype[name] = implementation;
            return this;
        }
    }

    var Person = function(name) {
        // body...
        this.name = name;
    }.method('getName',function(){
        return this.name;
    }).method('setName',function(){
        this.name = name;
        return this;
    });

    var ab  = new Person('hehhh');
    console.log(ab);
    console.log(typeof ab);
    ab.getName(); // 这个地方出错了,囧
    ab.setName('eve').getName();

    console.log(typeof Function.prototype.setName);
    console.log(typeof Function.prototype.getName);

请问一下,为什么我注释这个地方会出错。出错情况如标题。

javascript Uncaught TypeError: undefined is not a function

阿神阿神2900 days ago543

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-10 14:43:17

    var Person = function(name) {
        // body...
        this.name = name;
    }.method('getName',function(){ 
    // 第一次使用 method,this 返回了 Function.prototype.method 
        return this.name;
    }).method('setName',function(){ 
    // 这里变成了 Function.prototype.method.method,并没有设置 setName
        this.name = name;
        return this;
    });
    
    var ab = new Person('hehhh');
    console.log(ab); // 打印的值为:Person.method.method.name {name: "hehhh"}
    

    一般不建议使用 Function.prototype,可以试下用这种方式定义:

    var Person = function(name) {
        this.name = name;
    };
    Person.prototype = {
        getName: function() {
            return this.name;
        },
        setName: function(name) {
            this.name = name;
            return this;
        }
    };
    
    var ab  = new Person('hehhh');
    console.log(ab);
    console.log(typeof ab);
    console.log(ab.getName());
    console.log(ab.setName('eve').getName());
    

    reply
    0
  • Cancelreply