首页 > javascript Uncaught TypeError: undefined is not a function

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


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());

根据你对 Function做的扩展 method的实现代码,可以知道 它是给Function的原型上添加方法的.
所以在你后面的

ab.getName(); // 这个地方出错了,囧

不出错就怪了.
原因是在为 ab 是 Person 的一个实例

ab = new Person('hehhh')

它并不是一个function, 所以它没有 getName 和 setName 这两个方法,
而且也没有getName和setName这两个属性,所以当你取 ab.getName的时候, 得到的是 undefined,
所以结果就是: javascript Uncaught TypeError: undefined is not a function

你的代码,如果想正确运行, 只需要改一个地方, 把 Function.prototype 改为 this.prototype 即可.
(不过你后面的setName,没有指定参数,所以在 this.name = name;的时候,会报错).

【热门文章】
【热门文章】