原型方法中的“this”并不总是指对象本身的原型?

时间:2014-02-07 13:22:22

标签: coffeescript prototype this

大多数时候我只需要使用JavaScript就可以为简单的HTML添加一些动态。然而,最近,在发现CoffeeScript之后,我对*面向对象的JavaScript感兴趣“。这是CoffeeScript中的一些代码。

class MyClass
    constructor: (title, purpose)->
        @title = typeof title is undefined ? "My Class" : title
        @purpose = typeof purpose is undefined ? "None" : purpose
        @myMethod()

    myMethod: ->
        _getTitle = @getTitle
        _getPurpose = @getPurpose
        $(window).click ->
            _getTitle()
            _getPurpose()
            return
        return

    getTitle: ->
        _title = @title
        window.console.log "Title of the class this object belongs to is: #{_title}"
        return

    getPurpose: ->
        _purpose = @purpose
        window.console.log "Purpose of creating this class is: #{_purpose}"
        return

    title = ""
    purpose = ""

myObject = new MyClass("Testbed", "to test Object Oriented JavaScript")

对于喜欢JavaScript的人,这里是编译的(?)JavaScript。

var MyClass, myObject;

MyClass = (function() {
  var purpose, title;

  function MyClass(title, purpose) {
    var _ref, _ref1;
    this.title = (_ref = typeof title === void 0) != null ? _ref : {
      "My Class": title
    };
    this.purpose = (_ref1 = typeof purpose === void 0) != null ? _ref1 : {
      "None": purpose
    };
    this.myMethod();
  }

  MyClass.prototype.myMethod = function() {
    var _getPurpose, _getTitle;
    _getTitle = this.getTitle;
    _getPurpose = this.getPurpose;
    $(window).click(function() {
      _getTitle();
      _getPurpose();
    });
  };

  MyClass.prototype.getTitle = function() {
    var _title;
    _title = this.title;
    window.console.log("Title of the class this object belongs to is: " + _title);
  };

  MyClass.prototype.getPurpose = function() {
    var _purpose;
    _purpose = this.purpose;
    window.console.log("Purpose of creating this class is: " + _purpose);
  };

  title = "";

  purpose = "";

  return MyClass;

})();

myObject = new MyClass("Testbed", "to test Object Oriented JavaScript");

很抱歉长代码。我不得不试着让它变得有趣。问题是,这段代码输出:

Title of the class this object belongs to is: undefined
Purpose of creating this class is: undefined

而我期待它输出:

Title of the class this object belongs to is: Testbed
Purpose of creating this class is: to test Object Oriented JavaScript

我可以发誓当我上次使用它时(大约六个月前)它是如何工作的。我了解到,在作为对象的 prototype 一部分的方法中,this指的是原型本身。而this.something实际上会指向object.something。而在此示例中,在myObject.myMethod()内,this表现得应有尽有,this.getTitle()表示myObject.getTitle()。但是,在myObject.getTitle()内,this指的是window。为什么呢?

是因为在getTitle()处理程序中调用了$(window).click()吗?但为什么会改变背景呢? getTitle()仍然是myObject的属性。

另外,你看到我想在这里完成的事情。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

有几个问题。

1)您永远不会从.getPurpose.getTitle

返回任何内容

2)您应该在myMethod中创建对此的引用。即var me = this,然后在事件监听器调用me.getTitle()me.getPurpose()内。这是必需的,因为在事件监听器(窗口onclick)内部,这指的是窗口而不是对象。

3)看起来你的三元表达式总是在评估为false。你需要重新考虑它们。

P.S。我看了直接的JS版本