簡體   English   中英

javascript“基本面向對象”,回調和與此相關的問題,希望是一個很好的例子

[英]javascript “basic Object Oriented”, callbacks, and headache with this, hopefully a good example

請嘗試運行以下示例,因為我不是JavaScript專家,所以它“有點麻煩”,當嘗試使用“原始javascript”(更多的瀏覽器兼容性)來面向對象時。

您能否提供關於注釋行的經驗,問“什么更好”-意思是更清晰,編寫JavaScript時出錯更少。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<style>
</style>
<script>
function makeI(myId, myA) { 
  var I = {
    id: myId,
    A: myA,

    toString: function toString() { console.log('id:' +I.id+ ', A=' +this.A); return this;},
    //                                                 ^              ^
    //                                                 |              |
    //             What's better, more clear?       shorter      how does this help, just fools us on callbacks?
    // 
    oops: function oops() {
      document.getElementById('div').onclick = function() 
        { console.log('oops() A=' +this.A+ '   , darn! Well, the id=' +this.id+ " , NOT our/I's id"); }
    },

    f: function f() {
      document.getElementById('div').onclick = function() 
        { console.log('oops() A=' +I.A+ '  , good. Well, the id=' +I.id); }
    },
  }
  return I;
}
function try1() {
  console.log('---- try1() , my oops ---------');
  var i1 = makeI('1', 10).toString();
  i1.oops();
  console.log('OK, now please click on gold div, and watch the error\n');
}
function try2() {
  console.log('---- try2() ---------');
  var i2 = makeI('2', 20).toString(); 
  i2.f();
  console.log('OK, now please click on gold div\n');
}
</script>
</head>
<body>
<div onclick='try1()' style='border: 2px solid   red; width:400px;'>Please click, and see console output (oops!)</div><br>
<div onclick='try2()' style='border: 2px solid green; width:400px;'>Please click, and see console output, comments please</div><br>
<div id='div' style='border: 2px solid  gold; width:400px;'>div</div>
</body>
</html>

請注意,您的版本toStringoopsf都是不同的函數,它們綁定到I不同實例。 這是I.myId在您的情況下起作用的唯一原因。 但是,通常,我們更喜歡使用一個函數來調用該函數的不同值, this引擎就可以減少工作量(創建更少的單個函數)。

為了清楚和易於維護, 是首選的,尤其是面向對象的開發。

 class I { constructor(myId, myA) { this.id = myId; this.A = myA; } toString() { // NOTE: It's bad practice to not return a string from `toString()` console.log('id:' + this.id + ', A=' + this.A); return this; } oops() { document.getElementById('div').onclick = () => { console.log('oops() A=' + this.A + ' , darn! Well, the id=' + this.id + " , NOT our/I's id"); }; } f() { document.getElementById('div').onclick = () => { console.log('oops() A=' + this.A + ' , good. Well, the id=' + this.id); }; } } // NOTE: This function doesn't really do anything anymore; you can probably remove it function makeI(myId, myA) { return new I(myId, myA); } function try1() { console.log('---- try1() , my oops ---------'); var i1 = makeI('1', 10).toString(); i1.oops(); console.log('OK, now please click on gold div, and watch the errors\\n'); } function try2() { console.log('---- try2() ---------'); var i2 = makeI('2', 20).toString(); i2.f(); console.log('OK, now please click on gold div\\n'); } 
 <div onclick='try1()' style='border: 2px solid red; width:400px;'>Please click, and see console output (oops!)</div><br> <div onclick='try2()' style='border: 2px solid green; width:400px;'>Please click, and see console output, comments please</div><br> <div id='div' style='border: 2px solid gold; width:400px;'>div</div> 

如果您確實需要支持較舊的瀏覽器,建議您使用Babel將上述代碼轉換為向后兼容的JavaScript。 例如,當上面的類使用ie 6 ,您將獲得如下內容:

"use strict";

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var I =
/*#__PURE__*/
function () {
  function I(myId, myA) {
    _classCallCheck(this, I);

    this.id = myId;
    this.A = myA;
  }

  _createClass(I, [{
    key: "toString",
    value: function toString() {
      console.log('id:' + this.id + ', A=' + this.A);
      return this;
    }
  }, {
    key: "oops",
    value: function oops() {
      var _this = this;

      document.getElementById('div').onclick = function () {
        console.log('oops() A=' + _this.A + '   , darn! Well, the id=' + _this.id + " , NOT our/I's id");
      };
    }
  }, {
    key: "f",
    value: function f() {
      var _this2 = this;

      document.getElementById('div').onclick = function () {
        console.log('oops() A=' + _this2.A + '  , good. Well, the id=' + _this2.id);
      };
    }
  }]);

  return I;
}();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM