【问题标题】:Prototypes issue in javascriptjavascript中的原型问题
【发布时间】:2014-08-17 18:31:34
【问题描述】:

我刚刚开始学习 javascript 中的原型,但我无法理解我的代码中存在什么问题。对不起,我的问题可能看起来很傻

我收到这样的错误: Uncaught TypeError: undefined is not a function

为什么是未定义的?我继承了用户的功能。 看不懂:(

var user = {

    sayName: function() {
        console.log(this.name)
    }

  };

user.name = "viktor";

user.sayName();

var user2 = {};

user2.prototype = user;

user2.name = "segey";

user2.sayName();

【问题讨论】:

  • var user2 = Object.create(user)
  • prototype 属性与构造函数 functions 相关联,以便在创建 new 实例时使用,而不是与实例本身相关联。
  • .prototype 属性仅与函数真正相关。该函数在使用new 调用时会建立正在创建的新对象和函数的.prototype 对象之间的关系。 ...就像乔南森说的那样^^^

标签: javascript


【解决方案1】:

使用普通对象设置原型链所需的只是:

var user2 = Object.create(user); // set `user` as prototype of `user2`

user2.name = "segey";
user2.sayName();

【讨论】:

    【解决方案2】:

    对于您提出的问题,正确的解决方案将:

    function User() {
        this.name = 'Viktor';
        return this;
    }
    
    User.prototype = Object.create({
        sayName: function() {
            return this.name;
        }
    });
    
    function User2() {}
    User2.prototype = Object.create(User.prototype);
    
    var user = new User();
    user.sayName(); // 'Viktor'
    user2 = new User2();
    user2.name = 'Bogdan';
    user2.sayName(); // 'Bogdan'
    

    并以示例进行详细说明。 假设我们有一些基础课程Animal。我们的 Animal 有 agename

    function Animal() {
        this.age = 5;
        this.name = "Stuffy";
        return this;
    }
    
    Animal.prototype = Object.create({
        getAge: function() {
            return this.age;
        },
    
        getName: function() {
            return this.name;
        }
    });
    

    当我花一些时间在建筑上时,我明白我也需要动物的子类。例如,让它成为Dog 具有新属性和功能的类。而且Dog 必须从Animal 类扩展函数和属性。

    function Dog() {
        Animal.apply(this, arguments); // Call parent constructor
        this.wantsEat = true; // Add new properties
        return this;
    }
    
    Dog.prototype = Object.create(Animal.prototype); // Create object with Animal prototype
    Object.extend(Dog.prototype, { // Any extend() function, wish you want
        constructor: Dog, // Restore constructor for Dog class
        eat: function() {
            this.wantsEat = false;
            return this;
        }
    });
    

    或者你可以使用Object.defineProperties()并以这种方式扩展:

    Dog.prototype = Object.create(Animal.prototype, {
        constructor: {
            value: Dog
        },
    
        eat: {
            value: function() {
                this.wantsEat = false;
                return this;
            }
        }
    });
    

    【讨论】:

    • @Viktorino 如果您只是从原型开始,我认为这会有所帮助:)
    • 谢谢 :) 我的眼睛有点黑,但总的来说还可以)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    相关资源
    最近更新 更多