【问题标题】:Javascript - Change object with left-hand assignment in constructorJavascript - 在构造函数中使用左侧赋值更改对象
【发布时间】:2012-09-22 18:39:15
【问题描述】:

我一直在尝试各种方法来模拟 Javascript 中的经典继承,并且我已经找到了一些方法来做到这一点。但是,我很好奇为什么我不能以一种特定的方式做到这一点,以及如何尝试解决它。​​

我试过了:

var squeaker = new squeek();

function monsterMaker(newMonster) {
    newMonster.type = "monster";
    newMonster.health = 10;
    return newMonster;
}

function squeek() {
    this.name = "squeek";
    this = monsterMaker(this);
}

我想我明白为什么会发生这种情况,并且我已经找到了解决方法(即 jQuery 的 $.extend),但是有没有办法使用左手赋值以这种方式更改新创建的对象,或者一种解决方法,无需使用额外的库?

【问题讨论】:

  • 您无法更改此引用。

标签: javascript inheritance extends


【解决方案1】:

你不能分配给this,但你不需要:你的代码,如果它有效,将等同于这个有效的代码:

var squeaker = new squeek();

function monsterMaker(newMonster) {
    newMonster.type = "monster";
    newMonster.health = 10;
    return newMonster;
}

function squeek() {
    this.name = "squeek";
    monsterMaker(this); // sets properties on this
}

(虽然 JavaScript 是按值传递,但本例中的“值”是整个 this 对象,所以在某些方面它就像按引用传递。)

【讨论】:

  • monsterMaker 函数中不需要返回,因为调用函数已经引用了传递的对象,并且没有使用返回值。
  • @RobG:我不知道,我认为monsterMaker 支持被称为var monster = monsterMaker({}) 是非常明智的。您说“未使用返回值”,但我认为您无法真正知道;你只知道squeek 不使用它。
  • 调用可以传递一个“匿名”对象,但这在 OP 的上下文中没有多大意义。
【解决方案2】:

不,您不能分配给this。但是,您不需要!只需将实例 (this) 传递给 monsterMaker,该函数就会为其添加一些属性 - 正是您想要的。您不需要返回对象,或使用返回的对象 - 它仍然是 this。

function Squeek() {
    this.name = "squeek";
    monsterMaker(this);
}

new Squeek(); // will have type and health

【讨论】:

  • @user1689607:否 - Squeek 是一个构造函数。 return this 不会改变任何东西。
【解决方案3】:

你应该试试:

var squeaker = new squeek();

function monsterMaker(newMonster) {
    this.type = "monster";
    this.health = 10;
}

function squeek() {
    this.name = "squeek";
    monsterMaker.call(this);
}

这样,您可以使用 monsterMaker 函数的属性“装饰”您想要的任何对象。

但是,进一步思考,我认为您已经到了需要原型继承的地步......

【讨论】:

    【解决方案4】:

    这是一种使用原型继承的方法,.要查看控制台输出,请在 Chrome 中按 F12 或在 FireFox 中打开 FireBug。 Chrome 将为您提供一个交互式对象以进行深入研究。

    function monsterMaker() {
        this.type = "monster";
        this.health = 10;
    }
    
    function squeek() {
        this.name = "squeek";
        //monsterMaker.call(this); // sets properties on this
    }
    squeek.prototype = new monsterMaker();
    squeek.prototype.constructor = monsterMaker;
    
    var squeaker = new squeek();
    
    console.log(squeaker);
    console.log(squeaker.name);
    console.log(squeaker.type);
    console.log(squeaker.health);
    

    在这里查看它的工作原理:

    http://www.quirkscode.com/flat/forumPosts/extendThis/extendThis.html

    这里有一些链接:

    https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain

    https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_Revisited

    从上面的第二个 MDN 链接中提取,您可以使用“新 JavaScript 方式”(ECMAScript 5)来实现(包括用于扩展和示例代码的库 - 使用控制台查看示例输出:

    // Original Author:  FireFly - Jonas Höglund - ##javascript channel
    // on irc.freenode.net - see THANKS File
    
    ///////////////
    // Library code
    ///////////////
    
    var ExtendBase = {};
    
    Object.defineProperty(ExtendBase, 'extend', {
        enumerable: false
        , value: function(obj) {
            'use strict';
    
            var descs = {}
            , objectInheritCounter = 0;
    
            objectInheritCounter += 1;
    
            Object.getOwnPropertyNames(obj).forEach(function(key) {
            descs[key] = Object.getOwnPropertyDescriptor(obj, key)
            });
    
            return Object.create(this, descs);
        }
    });
    
    ///////////////
    // Sample Usage
    ///////////////
    
    var Person = ExtendBase.extend({
      // missing: name
    
      // A person can tell you its name.
      talk: function() {
        return "Hello, I'm " + this.name
      }
    })
    
    var WorkingPerson = Person.extend({
      // missing: name, occupation
    
      // A working person also tells you their occupation when they talk.
      talk: function() {
        return Person.talk.call(this) + " and I am a " + this.occupation
      }
    })
    
    var p1 = WorkingPerson.extend({ name:"Harry", occupation:"wizard" })
    console.log(p1.talk()); // "Hello, I'm Harry and I am a wizard"
    

    在这里查看它的工作原理:

    http://www.quirkscode.com/flat/JSLearning/src/extend/extend.html

    【讨论】:

    • Bergi:你能告诉我你为什么这么想吗?我不完全确定为什么 - 不是在争论,只是不确定你为什么这么说。谢谢。
    【解决方案5】:

    JavaScipt 是一种基于原型的语言。与其尝试模仿经典的面向对象语言,不如屈服于原型。

    在这种情况下,您要创建一个Monster 原型;以及基于Monster 原型的Squeek 原型。然后从Squeek 对象实例化一个squeaker。

    /* Set up your Monster prototype */
    function Monster() { /* constructor */}
    Monster.prototype.type = "monster";
    Monster.prototype.health = 10;
    
    /* Now use the prototype of a Monster to create the prototype of a Squeek */
    function Squeek() { /* constructor */ }
    Squeek.prototype = new Monster(); // thanks Bergi and RobG
    Squeek.prototype.constructor = Squeek; // thanks RobG
    Squeek.prototype.name = "squeek";
    
    /* Now let's instantiate a Squeek */
    var squeaker = new Squeek();
    console.log(squeaker.name); // squeek
    console.log(squeaker.type); // monster
    console.log(squeaker.health); // 10
    console.log(squeaker.constructor === Squeek); // true
    
    var monster = new Monster();
    console.log(monster.name); // undefined
    

    【讨论】:

    • 为什么将Monster.prototype.name设置为"squeek"?
    • 最好将Monster 的instance 分配给Squeek 的原型。此外,您想修改Squeek.prototype 的构造函数属性,因为这是Squeek 的实例将继承的属性。 Squeek 构造函数是内置 Function 对象的一个​​实例,因此它的构造函数属性(它继承自 [[Prototype]])应该引用。
    猜你喜欢
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 2016-01-17
    相关资源
    最近更新 更多