javascript Uncaught TypeError: undefined is not a function
阿神
阿神 2017-04-10 14:41:17
0
1
546
    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

阿神
阿神

闭关修行中......

Antworte allen(1)
伊谢尔伦
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());
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage