• JavaScript , js 上下文(this 的指代)


      上下文 代表 this 变量的值, 以及 它的 指代;

      它决定一个函数怎么被调用;

      当一个函数作为一个对象的方法被调用的时候, this总是指向 调用这个方法的对象.

    -----

    1 ,情况一: 字面量对象中的this

    1 var pet = {
    2     words: '...',
    3     speak: function(){
    4         console.log(this.words);
    5         console.log(this === pet);
    6     }
    7 }
    8 
    9 pet.speak();

     pet对象调用 speak方法,  this 指向 pet对象;  因此 this.words 等于 '...';

    this === pet  ,正确.

    2.情况二: 普通函数中的 this

     1 //2: 普通函数中的this
     2 
     3 function pet(words)
     4 {
     5     this.words = words;
     6 
     7     console.log(this.words);
     8     console.log(this === global);
     9 }
    10 
    11 pet('test,test');

      可见,在 作为普通函数使用的时候, this 是 指代 最顶级的全局变量的, 在 浏览器中是 window对象 ; 在node中 是 global.

    ---------------------------------------------------------------

    输出 global对象.

     1 //2: 普通函数中的this
     2 
     3 function pet(words)
     4 {
     5     this.words = words;
     6 
     7     console.log(this.words);
     8     console.log(this === global);
     9     console.log(global);
    10 }
    11 
    12 pet('test,test');
      1 D:
    ode>node context.js
      2 test,test
      3 true
      4 { DTRACE_NET_SERVER_CONNECTION: [Function],
      5   DTRACE_NET_STREAM_END: [Function],
      6   DTRACE_HTTP_SERVER_REQUEST: [Function],
      7   DTRACE_HTTP_SERVER_RESPONSE: [Function],
      8   DTRACE_HTTP_CLIENT_REQUEST: [Function],
      9   DTRACE_HTTP_CLIENT_RESPONSE: [Function],
     10   COUNTER_NET_SERVER_CONNECTION: [Function],
     11   COUNTER_NET_SERVER_CONNECTION_CLOSE: [Function],
     12   COUNTER_HTTP_SERVER_REQUEST: [Function],
     13   COUNTER_HTTP_SERVER_RESPONSE: [Function],
     14   COUNTER_HTTP_CLIENT_REQUEST: [Function],
     15   COUNTER_HTTP_CLIENT_RESPONSE: [Function],
     16   global: [Circular],
     17   process:
     18    process {
     19      title: 'C:\WINDOWS\system32\cmd.exe - node  context.js',
     20      version: 'v4.5.0',
     21      moduleLoadList:
     22       [ 'Binding contextify',
     23         'Binding natives',
     24         'NativeModule events',
     25         'NativeModule buffer',
     26         'Binding buffer',
     27         'NativeModule internal/util',
     28         'Binding util',
     29         'NativeModule timers',
     30         'Binding timer_wrap',
     31         'NativeModule _linklist',
     32         'NativeModule assert',
     33         'NativeModule util',
     34         'Binding uv',
     35         'NativeModule path',
     36         'NativeModule module',
     37         'NativeModule internal/module',
     38         'NativeModule vm',
     39         'NativeModule fs',
     40         'Binding fs',
     41         'NativeModule constants',
     42         'Binding constants',
     43         'NativeModule stream',
     44         'NativeModule _stream_readable',
     45         'NativeModule _stream_writable',
     46         'NativeModule _stream_duplex',
     47         'NativeModule _stream_transform',
     48         'NativeModule _stream_passthrough',
     49         'Binding fs_event_wrap',
     50         'NativeModule console',
     51         'Binding tty_wrap',
     52         'NativeModule tty',
     53         'NativeModule net',
     54         'NativeModule internal/net',
     55         'Binding cares_wrap',
     56         'Binding tcp_wrap',
     57         'Binding pipe_wrap',
     58         'Binding stream_wrap',
     59         'Binding signal_wrap' ],
     60      versions:
     61       { http_parser: '2.7.0',
     62         node: '4.5.0',
     63         v8: '4.5.103.37',
     64         uv: '1.9.1',
     65         zlib: '1.2.8',
     66         ares: '1.10.1-DEV',
     67         icu: '56.1',
     68         modules: '46',
     69         openssl: '1.0.2h' },
     70      arch: 'x64',
     71      platform: 'win32',
     72      release:
     73       { name: 'node',
     74         lts: 'Argon',
     75         sourceUrl: 'https://nodejs.org/download/release/v4.5.0/node-v4.5.0.tar.gz',
     76         headersUrl: 'https://nodejs.org/download/release/v4.5.0/node-v4.5.0-headers.tar.gz',
     77         libUrl: 'https://nodejs.org/download/release/v4.5.0/win-x64/node.lib' },
     78      argv:
     79       [ 'D:\Program Files\nodejs\node.exe',
     80         'D:\node\context.js' ],
     81      execArgv: [],
     82      env:
     83       { ALLUSERSPROFILE: 'C:\ProgramData',
     84         APPDATA: 'C:\Users\dc5yy\AppData\Roaming',
     85         CommonProgramFiles: 'C:\Program Files\Common Files',
     86         'CommonProgramFiles(x86)': 'C:\Program Files (x86)\Common Files',
     87         CommonProgramW6432: 'C:\Program Files\Common Files',
     88         COMPUTERNAME: 'DESKTOP-2I328NT',
     89         ComSpec: 'C:\WINDOWS\system32\cmd.exe',
     90         configsetroot: 'C:\WINDOWS\ConfigSetRoot',
     91         FPS_BROWSER_APP_PROFILE_STRING: 'Internet Explorer',
     92         FPS_BROWSER_USER_PROFILE_STRING: 'Default',
     93         HOMEDRIVE: 'C:',
     94         HOMEPATH: '\Users\dc5yy',
     95         LOCALAPPDATA: 'C:\Users\dc5yy\AppData\Local',
     96         LOGONSERVER: '\\DESKTOP-2I328NT',
     97         MOZ_PLUGIN_PATH: 'C:\Program Files (x86)\Foxit Software\Foxit Reader\plugins\',
     98         NUMBER_OF_PROCESSORS: '4',
     99         OneDrive: 'C:\Users\dc5yy\OneDrive',
    100         OS: 'Windows_NT',
    101         Path: 'C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;D:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\VisualSVN Server\bin;D:\Program Files\nodejs\;C:\Users\dc5yy\AppData\Roaming\npm;C:\Users\dc5yy\AppData\Local\Microsoft\WindowsApps;D:\xampp\apache\bin',
    102         PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC',
    103         PROCESSOR_ARCHITECTURE: 'AMD64',
    104         PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 60 Stepping 3, GenuineIntel',
    105         PROCESSOR_LEVEL: '6',
    106         PROCESSOR_REVISION: '3c03',
    107         ProgramData: 'C:\ProgramData',
    108         ProgramFiles: 'C:\Program Files',
    109         'ProgramFiles(x86)': 'C:\Program Files (x86)',
    110         ProgramW6432: 'C:\Program Files',
    111         PROMPT: '$P$G',
    112         PSModulePath: 'C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules',
    113         PUBLIC: 'C:\Users\Public',
    114         SESSIONNAME: 'Console',
    115         SystemDrive: 'C:',
    116         SystemRoot: 'C:\WINDOWS',
    117         TEMP: 'C:\Users\dc5yy\AppData\Local\Temp',
    118         TMP: 'C:\Users\dc5yy\AppData\Local\Temp',
    119         USERDOMAIN: 'DESKTOP-2I328NT',
    120         USERDOMAIN_ROAMINGPROFILE: 'DESKTOP-2I328NT',
    121         USERNAME: 'admin',
    122         USERPROFILE: 'C:\Users\dc5yy',
    123         VISUALSVN_SERVER: 'C:\Program Files (x86)\VisualSVN Server\',
    124         windir: 'C:\WINDOWS' },
    125      pid: 7292,
    126      features:
    127       { debug: false,
    128         uv: true,
    129         ipv6: true,
    130         tls_npn: true,
    131         tls_sni: true,
    132         tls_ocsp: true,
    133         tls: true },
    134      _needImmediateCallback: false,
    135      execPath: 'D:\Program Files\nodejs\node.exe',
    136      debugPort: 5858,
    137      _startProfilerIdleNotifier: [Function: _startProfilerIdleNotifier],
    138      _stopProfilerIdleNotifier: [Function: _stopProfilerIdleNotifier],
    139      _getActiveRequests: [Function: _getActiveRequests],
    140      _getActiveHandles: [Function: _getActiveHandles],
    141      reallyExit: [Function: reallyExit],
    142      abort: [Function: abort],
    143      chdir: [Function: chdir],
    144      cwd: [Function: cwd],
    145      umask: [Function: umask],
    146      _kill: [Function: _kill],
    147      _debugProcess: [Function: _debugProcess],
    148      _debugPause: [Function: _debugPause],
    149      _debugEnd: [Function: _debugEnd],
    150      hrtime: [Function: hrtime],
    151      dlopen: [Function: dlopen],
    152      uptime: [Function: uptime],
    153      memoryUsage: [Function: memoryUsage],
    154      binding: [Function: binding],
    155      _linkedBinding: [Function: _linkedBinding],
    156      _setupDomainUse: [Function: _setupDomainUse],
    157      _events:
    158       { newListener: [Function],
    159         removeListener: [Function],
    160         SIGWINCH: [Object] },
    161      _rawDebug: [Function],
    162      _eventsCount: 3,
    163      domain: null,
    164      _maxListeners: undefined,
    165      EventEmitter:
    166       { [Function: EventEmitter]
    167         EventEmitter: [Circular],
    168         usingDomains: false,
    169         defaultMaxListeners: 10,
    170         init: [Function],
    171         listenerCount: [Function] },
    172      _fatalException: [Function],
    173      _exiting: false,
    174      assert: [Function],
    175      config: { target_defaults: [Object], variables: [Object] },
    176      nextTick: [Function: nextTick],
    177      _tickCallback: [Function: _tickCallback],
    178      _tickDomainCallback: [Function: _tickDomainCallback],
    179      stdout: [Getter],
    180      stderr: [Getter],
    181      stdin: [Getter],
    182      openStdin: [Function],
    183      exit: [Function],
    184      kill: [Function],
    185      mainModule:
    186       Module {
    187         id: '.',
    188         exports: {},
    189         parent: null,
    190         filename: 'D:\node\context.js',
    191         loaded: false,
    192         children: [],
    193         paths: [Object] } },
    194   GLOBAL: [Circular],
    195   root: [Circular],
    196   Buffer:
    197    { [Function: Buffer]
    198      poolSize: 8192,
    199      from: [Function],
    200      alloc: [Function],
    201      allocUnsafe: [Function],
    202      allocUnsafeSlow: [Function],
    203      isBuffer: [Function: isBuffer],
    204      compare: [Function: compare],
    205      isEncoding: [Function],
    206      concat: [Function],
    207      byteLength: [Function: byteLength] },
    208   clearImmediate: [Function],
    209   clearInterval: [Function],
    210   clearTimeout: [Function],
    211   setImmediate: [Function],
    212   setInterval: [Function],
    213   setTimeout: [Function],
    214   console: [Getter],
    215   words: 'test,test' }

     看 215行,  global对象中存在一个属性: words ;   这是因为我们执行了赋值操作 this.words = words.

    --------------------------------------------------------------

    如果不执行 this.words = words;

     1 //2: 普通函数中的this
     2 
     3 function pet(words)
     4 {
     5     // this.words = words;
     6 
     7     console.log(this.words);
     8     console.log(this === global);
     9     console.log(global);
    10 }
    11 
    12 pet('test,test');

    输出结果:

      1 D:
    ode>node context.js
      2 undefined
      3 true
      4 { DTRACE_NET_SERVER_CONNECTION: [Function],
      5   DTRACE_NET_STREAM_END: [Function],
      6   DTRACE_HTTP_SERVER_REQUEST: [Function],
      7   DTRACE_HTTP_SERVER_RESPONSE: [Function],
      8   DTRACE_HTTP_CLIENT_REQUEST: [Function],
      9   DTRACE_HTTP_CLIENT_RESPONSE: [Function],
     10   COUNTER_NET_SERVER_CONNECTION: [Function],
     11   COUNTER_NET_SERVER_CONNECTION_CLOSE: [Function],
     12   COUNTER_HTTP_SERVER_REQUEST: [Function],
     13   COUNTER_HTTP_SERVER_RESPONSE: [Function],
     14   COUNTER_HTTP_CLIENT_REQUEST: [Function],
     15   COUNTER_HTTP_CLIENT_RESPONSE: [Function],
     16   global: [Circular],
     17   process:
     18    process {
     19      title: 'C:\WINDOWS\system32\cmd.exe - node  context.js',
     20      version: 'v4.5.0',
     21      moduleLoadList:
     22       [ 'Binding contextify',
     23         'Binding natives',
     24         'NativeModule events',
     25         'NativeModule buffer',
     26         'Binding buffer',
     27         'NativeModule internal/util',
     28         'Binding util',
     29         'NativeModule timers',
     30         'Binding timer_wrap',
     31         'NativeModule _linklist',
     32         'NativeModule assert',
     33         'NativeModule util',
     34         'Binding uv',
     35         'NativeModule path',
     36         'NativeModule module',
     37         'NativeModule internal/module',
     38         'NativeModule vm',
     39         'NativeModule fs',
     40         'Binding fs',
     41         'NativeModule constants',
     42         'Binding constants',
     43         'NativeModule stream',
     44         'NativeModule _stream_readable',
     45         'NativeModule _stream_writable',
     46         'NativeModule _stream_duplex',
     47         'NativeModule _stream_transform',
     48         'NativeModule _stream_passthrough',
     49         'Binding fs_event_wrap',
     50         'NativeModule console',
     51         'Binding tty_wrap',
     52         'NativeModule tty',
     53         'NativeModule net',
     54         'NativeModule internal/net',
     55         'Binding cares_wrap',
     56         'Binding tcp_wrap',
     57         'Binding pipe_wrap',
     58         'Binding stream_wrap',
     59         'Binding signal_wrap' ],
     60      versions:
     61       { http_parser: '2.7.0',
     62         node: '4.5.0',
     63         v8: '4.5.103.37',
     64         uv: '1.9.1',
     65         zlib: '1.2.8',
     66         ares: '1.10.1-DEV',
     67         icu: '56.1',
     68         modules: '46',
     69         openssl: '1.0.2h' },
     70      arch: 'x64',
     71      platform: 'win32',
     72      release:
     73       { name: 'node',
     74         lts: 'Argon',
     75         sourceUrl: 'https://nodejs.org/download/release/v4.5.0/node-v4.5.0.tar.gz',
     76         headersUrl: 'https://nodejs.org/download/release/v4.5.0/node-v4.5.0-headers.tar.gz',
     77         libUrl: 'https://nodejs.org/download/release/v4.5.0/win-x64/node.lib' },
     78      argv:
     79       [ 'D:\Program Files\nodejs\node.exe',
     80         'D:\node\context.js' ],
     81      execArgv: [],
     82      env:
     83       { ALLUSERSPROFILE: 'C:\ProgramData',
     84         APPDATA: 'C:\Users\dc5yy\AppData\Roaming',
     85         CommonProgramFiles: 'C:\Program Files\Common Files',
     86         'CommonProgramFiles(x86)': 'C:\Program Files (x86)\Common Files',
     87         CommonProgramW6432: 'C:\Program Files\Common Files',
     88         COMPUTERNAME: 'DESKTOP-2I328NT',
     89         ComSpec: 'C:\WINDOWS\system32\cmd.exe',
     90         configsetroot: 'C:\WINDOWS\ConfigSetRoot',
     91         FPS_BROWSER_APP_PROFILE_STRING: 'Internet Explorer',
     92         FPS_BROWSER_USER_PROFILE_STRING: 'Default',
     93         HOMEDRIVE: 'C:',
     94         HOMEPATH: '\Users\dc5yy',
     95         LOCALAPPDATA: 'C:\Users\dc5yy\AppData\Local',
     96         LOGONSERVER: '\\DESKTOP-2I328NT',
     97         MOZ_PLUGIN_PATH: 'C:\Program Files (x86)\Foxit Software\Foxit Reader\plugins\',
     98         NUMBER_OF_PROCESSORS: '4',
     99         OneDrive: 'C:\Users\dc5yy\OneDrive',
    100         OS: 'Windows_NT',
    101         Path: 'C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;D:\Program Files\TortoiseSVN\bin;C:\Program Files (x86)\VisualSVN Server\bin;D:\Program Files\nodejs\;C:\Users\dc5yy\AppData\Roaming\npm;C:\Users\dc5yy\AppData\Local\Microsoft\WindowsApps;D:\xampp\apache\bin',
    102         PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC',
    103         PROCESSOR_ARCHITECTURE: 'AMD64',
    104         PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 60 Stepping 3, GenuineIntel',
    105         PROCESSOR_LEVEL: '6',
    106         PROCESSOR_REVISION: '3c03',
    107         ProgramData: 'C:\ProgramData',
    108         ProgramFiles: 'C:\Program Files',
    109         'ProgramFiles(x86)': 'C:\Program Files (x86)',
    110         ProgramW6432: 'C:\Program Files',
    111         PROMPT: '$P$G',
    112         PSModulePath: 'C:\Program Files\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules',
    113         PUBLIC: 'C:\Users\Public',
    114         SESSIONNAME: 'Console',
    115         SystemDrive: 'C:',
    116         SystemRoot: 'C:\WINDOWS',
    117         TEMP: 'C:\Users\dc5yy\AppData\Local\Temp',
    118         TMP: 'C:\Users\dc5yy\AppData\Local\Temp',
    119         USERDOMAIN: 'DESKTOP-2I328NT',
    120         USERDOMAIN_ROAMINGPROFILE: 'DESKTOP-2I328NT',
    121         USERNAME: 'admin',
    122         USERPROFILE: 'C:\Users\dc5yy',
    123         VISUALSVN_SERVER: 'C:\Program Files (x86)\VisualSVN Server\',
    124         windir: 'C:\WINDOWS' },
    125      pid: 3864,
    126      features:
    127       { debug: false,
    128         uv: true,
    129         ipv6: true,
    130         tls_npn: true,
    131         tls_sni: true,
    132         tls_ocsp: true,
    133         tls: true },
    134      _needImmediateCallback: false,
    135      execPath: 'D:\Program Files\nodejs\node.exe',
    136      debugPort: 5858,
    137      _startProfilerIdleNotifier: [Function: _startProfilerIdleNotifier],
    138      _stopProfilerIdleNotifier: [Function: _stopProfilerIdleNotifier],
    139      _getActiveRequests: [Function: _getActiveRequests],
    140      _getActiveHandles: [Function: _getActiveHandles],
    141      reallyExit: [Function: reallyExit],
    142      abort: [Function: abort],
    143      chdir: [Function: chdir],
    144      cwd: [Function: cwd],
    145      umask: [Function: umask],
    146      _kill: [Function: _kill],
    147      _debugProcess: [Function: _debugProcess],
    148      _debugPause: [Function: _debugPause],
    149      _debugEnd: [Function: _debugEnd],
    150      hrtime: [Function: hrtime],
    151      dlopen: [Function: dlopen],
    152      uptime: [Function: uptime],
    153      memoryUsage: [Function: memoryUsage],
    154      binding: [Function: binding],
    155      _linkedBinding: [Function: _linkedBinding],
    156      _setupDomainUse: [Function: _setupDomainUse],
    157      _events:
    158       { newListener: [Function],
    159         removeListener: [Function],
    160         SIGWINCH: [Object] },
    161      _rawDebug: [Function],
    162      _eventsCount: 3,
    163      domain: null,
    164      _maxListeners: undefined,
    165      EventEmitter:
    166       { [Function: EventEmitter]
    167         EventEmitter: [Circular],
    168         usingDomains: false,
    169         defaultMaxListeners: 10,
    170         init: [Function],
    171         listenerCount: [Function] },
    172      _fatalException: [Function],
    173      _exiting: false,
    174      assert: [Function],
    175      config: { target_defaults: [Object], variables: [Object] },
    176      nextTick: [Function: nextTick],
    177      _tickCallback: [Function: _tickCallback],
    178      _tickDomainCallback: [Function: _tickDomainCallback],
    179      stdout: [Getter],
    180      stderr: [Getter],
    181      stdin: [Getter],
    182      openStdin: [Function],
    183      exit: [Function],
    184      kill: [Function],
    185      mainModule:
    186       Module {
    187         id: '.',
    188         exports: {},
    189         parent: null,
    190         filename: 'D:\node\context.js',
    191         loaded: false,
    192         children: [],
    193         paths: [Object] } },
    194   GLOBAL: [Circular],
    195   root: [Circular],
    196   Buffer:
    197    { [Function: Buffer]
    198      poolSize: 8192,
    199      from: [Function],
    200      alloc: [Function],
    201      allocUnsafe: [Function],
    202      allocUnsafeSlow: [Function],
    203      isBuffer: [Function: isBuffer],
    204      compare: [Function: compare],
    205      isEncoding: [Function],
    206      concat: [Function],
    207      byteLength: [Function: byteLength] },
    208   clearImmediate: [Function],
    209   clearInterval: [Function],
    210   clearTimeout: [Function],
    211   setImmediate: [Function],
    212   setInterval: [Function],
    213   setTimeout: [Function],
    214   console: [Getter] }
    215 
    216 D:
    ode>

     可见,此时 global对象中没有 words属性,  因此 输出 this.words 是 undefined.

    --------------------------------------

     3. 情况三: 构造函数中的this .

     1 //3: 构造函数中的this
     2 
     3 function Pet(words)
     4 {
     5     this.words = words;
     6     this.speak = function(){
     7         console.log(this.words);
     8         console.log(this);
     9         console.log(this === cat);
    10     }
    11 }
    12 
    13 var cat = new Pet("miao,miao");
    14 cat.speak();

      构造函数中的this 指的是 这个构造函数的 一个 实例.

    4: 通过 call 改变一个 函数中的this 的指代.

    4-1: 字面量对象:

     1 //1: call : 改变一个函数中的this的指代:
     2 
     3 var pet = {
     4     words: '...',
     5     speak: function(say){
     6         console.log(say + ' ' + this.words);
     7     }
     8 };
     9 
    10 pet.speak('Speak');
    11 
    12 var dog = {
    13     words: 'wang,wang'
    14 };
    15 
    16 pet.speak.call(dog, 'dog speaks');
    17 
    18 console.log(dog);
    19 
    20 pet.speak('pet speak again');

    运行:

     pet.speak.call(dog, 'dog speaks');

    显然:

      1. dog 对象 没有 speak方法,  如果使用 dog.speak()报错.

        

      2.pet.speak.call(dog, 'dog speaks'); 

        这句话的意思是   pet.speak 方法 的 this 指代发生变更,  从 pet  对象, 改为  dog 对象;

        同时 'dog speaks' 是给 pet.speak方法传递的参数.

      3. 这里  pet.speak.call(dog, 'dog speaks');   是 一次性的.

        3-1: 从第 20行 ,可以看出this 又 指向了pet对象.

        3-2: 从 18行可以看出, 使用call 将 pet.speak 中的this改变,从pet对象改为 dog 对象后. 

          dog对象 自己 并没有 增加 speak 方法.

             仅仅只是 对象 可以 通过 call  调用 其他对象的方法, 同时将该方法中的this 指代 自己.

        格式:   其他对象 . 方法 . call(当前对象, 传递给方法的参数);

    ------------------------------------------

     1 //1: call : 改变一个函数中的this的指代:
     2 
     3 var pet = {
     4     words: '...',
     5     speak: function(say){
     6         console.log(say + ' ' + this.words);
     7         console.log(this === dog);
     8     }
     9 };
    10 
    11 pet.speak('Speak');
    12 
    13 var dog = {
    14     words: 'wang,wang'
    15 };
    16 // dog.speak('dog, dog');
    17 pet.speak.call(dog, 'dog speaks');
    18 
    19 console.log(dog);
    20 
    21 // pet.speak('pet speak again');

     4-2: 构造函数:

     1 //1: call : 改变一个函数中的this的指代:
     2 
     3 //1-1: 字面量对象:
     4 // var pet = {
     5 //     words: '...',
     6 //     speak: function(say){
     7 //         console.log(say + ' ' + this.words);
     8 //         console.log(this === dog);
     9 //     }
    10 // };
    11 
    12 // pet.speak('Speak');
    13 
    14 // var dog = {
    15 //     words: 'wang,wang'
    16 // };
    17 // // dog.speak('dog, dog');
    18 // pet.speak.call(dog, 'dog speaks');
    19 
    20 // console.log(dog);
    21 
    22 // pet.speak('pet speak again');
    23 
    24 //1-2: 构造函数
    25 function Pet(words){
    26     this.words = words;
    27     this.speak = function(say){
    28         console.log(say + ' : '+ this.words);
    29         console.log(this === dog01);
    30     };
    31 }
    32 
    33 var pet01 = new Pet('this is pet');
    34 pet01.speak('pet speak');
    35 
    36 function Dog(words){
    37     this.words = words;
    38 }
    39 
    40 var dog01 = new Dog('this is dog');
    41 
    42 pet01.speak.call(dog01, 'dog speak');
    43 console.log(dog01);

     

        

     5. 通过 call 实现继承.

     1 //2: call: 实现继承:
     2 
     3 
     4 function Pet(words, age){
     5     this.words = words;
     6     this.age = age;
     7     this.speak = function(say){
     8         console.log(say + ' : '+ this.words);
     9     };
    10 }
    11 
    12 var pet = new Pet('this is pet', '4');
    13 pet.speak('pet speaks');
    14 console.log(pet);
    15 
    16 function Dog(words, age, color){
    17     this.color = color;
    18     Pet.call(this, words, age);
    19     // Pet.apply(this, [words, age]);
    20 }
    21 
    22 var dog = new Dog("this is dog", 2, 'yellow');
    23 dog.speak('dog speaks');
    24 console.log(dog);

    运行:

     注意:

      1.Pet.call(this, words, age);   格式是  :    其他构造函数(被继承的构造函数) . call (this当前构造函数, 传递给 被继承的构造函数的参数).

      2. call  和 apply的区别是 call 的参数是字符串, 多个,     ;  apply的参数是 一个数组.

      

       3.通过  被继承构造函数 . call (继承的构造函数, 参数) 后  ,

        继承的构造函数  就会 具有 被继承的构造函数中的 属性 和 方法.

     

    参考链接:

            上下文.

     

  • 相关阅读:
    js中有关类、对象的增强函数
    ES6学习准备
    JavaScript中类型检测
    网页性能优化
    前端工程化
    2014年度总结和计划
    vim命令汇总
    互联网思维
    传统企业信息化
    创业这三年¥.NET之尴尬处境
  • 原文地址:https://www.cnblogs.com/cbza/p/7280100.html
Copyright © 2020-2023  润新知