function(){} 和 () => {} 中this指向的问题

本文详细解析了JavaScript中this关键字的行为特性及其在不同函数调用方式下的表现,并对比了普通函数与箭头函数中this指向的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

普通函数中this

1. this总是代表它的直接调用者(js的this是执行上下文), 例如 obj.func ,那么func中的this就是obj

2.在默认情况(非严格模式下,未使用 'use strict'),没找到直接调用者,则this指的是 window (约定俗成)

3.在严格模式下,没有直接调用者的函数中的this是 undefined

4.使用call,apply,bind(ES5新增)绑定的,this指的是 绑定的对象

注意:普通函数中,内层函数不能从外层函数中继承this的值,在内层函数中,this会是window或者undefined,临时变量self用来将外部的this值导入到内部函数中(另外的方式是在内部函数执行.bind(this)

es6箭头函数

箭头函数没有自己的this, 它的this是继承而来; 默认指向在定义它时所处的对象(宿主对象),而不是执行时的对象, 定义它的时候,可能环境是window; 箭头函数可以方便地让我们在 setTimeout ,setInterval中方便的使用this。

===========================================================================

当在函数中使用一个变量的时候,首先在本函数内部查找该变量,如果找不到则找其父级函数,

最后直到window,全局变量默认挂载在window对象下


下面几个例子

1、普通函数中内层函数

function fun(){
    var self = this;
    setTimeout(function(){
        console.log(this);// window
        console.log(self);// {id: 001}
        console.log('id: ', self.id);// id:001
    },500);
}
fun.call({id:001});

2、普通函数中内层函数.bind(this)

function fun(){
    var self = this;
    setTimeout(function(){
        console.log(this); //{id: 1}
        console.log(self); //{id: 1}
        console.log('id: ', self.id); //id: 1
    }.bind(this),500);
}
fun.call({id:001});

3、

function fun(){
    /*setTimeout(() =>{
        console.log("args:",arguments); //args:[2,2,3,4]
    },500);*/
    setTimeout(function(){
        console.log("args:",arguments); //
    },500);
}
fun(2,2,3,4);

4、

var obj = {
   say: function () {
     setTimeout(() => {
       console.log(this)
     });
   }
 }
 obj.say(); // obj

5、

var obj = {
say: function () {
  var f1 = () => {
    console.log(this); // obj
    setTimeout(() => {
      console.log(this); // obj
    })
  }
  f1();
  }
}
obj.say()

6、

var obj = {
say: function () {
  var f1 = function () {
    console.log(this); // window, f1调用时,没有宿主对象,默认是window
    setTimeout(() => {
      console.log(this); // window
    })
  };
  f1();
  }
}
obj.say()

7、

var obj = {
say: function () {
  'use strict';
  var f1 = function () {
  console.log(this); // undefined
  setTimeout(() => {
    console.log(this); // undefined
  })
  };
  f1();
 }
}
obj.say()

8、总结例子

var a = 'window';
var id = '1';
var obj2 = {
	id: '2',
	a: 'obj2'
}
var obj = {
	a: 'obj',
	id: '3',
	say1: () => {
		console.log(this.a);
		console.log(this.id);
	},
	say2: function() {
		var f1 = () => {
			console.log(this.a);
			console.log(this.id);
		}
		f1();
	},
	say3: () => {
		var f1 = () => {
			console.log(this.a);
			console.log(this.id);
		}
		f1();
	}
}
console.log('================================');
obj.say1.call(obj2)
console.log('================================');
obj.say2.call(obj2)
console.log('================================');
obj.say3.call(obj2)
console.log('================================');
obj.say1()
console.log('================================');
obj.say2()
console.log('================================');
obj.say3()
console.log('================================');



[71]"D:/Work/CCS/ccs_20/ccs/tools/compiler/ti-cgt-armllvm_4.0.3.LTS/bin/tiarmclang.exe" -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -mlittle-endian -mthumb -gdwarf-3 -march=armv7e-m -Wl,-m"simple_tx_rfprop.map" -Wl,-i"D:/Work/SatIoT/CC1352/SDK/simplelink_cc13xx_cc26xx_sdk_8_30_01_01/source" -Wl,-i"D:/Work/SatIoT/CC1352/SDK/simplelink_cc13xx_cc26xx_sdk_8_30_01_01/kernel/tirtos7/packages" -Wl,-i"D:/Work/Project/jiang/bload-master/simple_tx_rfprop/Debug/syscfg" -Wl,-i"D:/Work/CCS/ccs_20/ccs/tools/compiler/ti-cgt-armllvm_4.0.3.LTS/lib" -Wl,--diag_wrap=off -Wl,--display_error_number -Wl,--warn_sections -Wl,--xml_link_info="simple_tx_rfprop_linkInfo.xml" -Wl,--rom_model -o "simple_tx_rfprop.out" "./main_tirtos.o" "./rfPacketTx.o" "./syscfg/ti_devices_config.o" "./syscfg/ti_radio_config.o" "./syscfg/ti_drivers_config.o" "./syscfg/ti_sysbios_config.o" "./oad/bim_interface.o" "./oad/flash_interface.o" "./oad/oad_image_header.o" "./oad/upgrade_manager.o" "../cc13x2_cc26x2_tirtos7_active.cmd" -Wl,-lti_utils_build_linker.cmd.genlibs -Wl,-llibc.a [72]gmake[1]: *** No rule to make target 'input-file.error', needed by 'output-file.error'. [73]Finished building target: "simple_tx_rfprop.out" [74]D:/Work/CCS/ccs_20/ccs/tools/compiler/ti-cgt-armllvm_4.0.3.LTS/bin/tiarmobjcopy -O ihex simple_tx_rfprop.out simple_tx_rfprop.hexD:/Work/SatIoT/CC1352/SDK/simplelink_cc13xx_cc26xx_sdk_8_30_01_01/tools/common/oad/oad_image_tool --verbose ccs D:/Work/Project/jiang/bload-master/simple_tx_rfprop/Debug 7 -hex1 D:/Work/Project/jiang/bload-master/simple_tx_rfprop/Debug/simple_tx_rfprop.hex -k D:/Work/SatIoT/CC1352/SDK/simplelink_cc13xx_cc26xx_sdk_8_30_01_01/tools/common/oad/private.pem -o D:/Work/Project/jiang/bload-master/simple_tx_rfprop/Debug/simple_tx_rfprop_oad [75]OVERVIEW: llvm-objcopy tool [76]USAGE: llvm-objcopy [options] input [output] [77]OPTIONS: [78] --add-gnu-debuglink=debug-file [79] Add a .gnu_debuglink for <debug-file&gt; [80] --add-note-segment=file Make a note segment with the contents of <file&gt;. [81] --add-section=section=file [82] Make a section named <section&gt; with the contents of <file&gt; [83] --add-symbol=name=[section:]value[,flags] [84] Add new symbol <name&gt; to .symtab. Accepted flags: global, local, weak, default, hidden, protected, file, section, object, function, indirect-function. Accepted but ignored for compatibility: debug, constructor, warning, indirect, synthetic, unique-object, before [85] --adjust-start <value&gt; Alias for --change-start [86] --allow-broken-links Allow the tool to remove sections even if it would leave invalid section references. The appropriate sh_link fields will be set to zero. [87] --binary-architecture=<value&gt; [88] Ignored for compatibility [89] -B <value&gt; Alias for --binary-architecture [90] --change-start=incr Add <incr&gt; to the start address. Can be specified multiple times, all values will be applied cumulatively [91] --compress-debug-sections=format [92] Compress DWARF debug sections using specified format. Supported formats: zlib, zstd. Select zlib if <format&gt; is omitted [93] --core-exe=coreid:filename [94] Specify an ELF executable for a Core ID as input. [95] --decompress-debug-sections [96] Decompress DWARF debug sections [97] --disable-deterministic-archives [98] Disable deterministic mode when operating on archives (use real values for UIDs, GIDs, and timestamps). [99] --discard-all Remove all local symbols except file and section symbols. Also remove all debug sections [100] --discard-locals Remove compiler-generated local symbols, (e.g. symbols starting with .L) [101] --dump-mmELFConfig Dump the contents of the internal mmELFConfig structure. [102] --dump-section=section=file [103] Dump contents of section named <section&gt; into file <file&gt; [104] -D Alias for --enable-deterministic-archives [105] --enable-deterministic-archives [106] Enable deterministic mode when operating on archives (use zero for UIDs, GIDs, and timestamps). [107] --extract-dwo Remove all sections that are not DWARF .dwo sections from file [108] --extract-main-partition [109] Extract main partition from the input file [110] --extract-partition=name [111] Extract named partition from input file [112] -F <value&gt; Alias for --target [113] --gap-fill=value Fill the gaps between sections with <value&gt; instead of zero. <value&gt; must be an unsigned 8-bit integer. This option is only supported for ELF input and binary output [114] --globalize-symbol=symbol [115] Mark <symbol&gt; as global [116] --globalize-symbols=filename [117] Reads a list of symbols from <filename&gt; and marks them global [118] -G <value&gt; Alias for --keep-global-symbol [119] -g Alias for --strip-debug [120] --input-target=<value&gt; Format of the input file [121] -I <value&gt; Alias for --input-target [122] -j <value&gt; Alias for --only-section [123] --keep-file-symbols Do not remove file symbols [124] --keep-global-symbol=symbol [125] Convert all symbols except <symbol&gt; to local. May be repeated to convert all except a set of symbols to local [126] --keep-global-symbols=filename [127] Reads a list of symbols from <filename&gt; and runs as if --keep-global-symbol=<symbol&gt; is set for each one. <filename&gt; contains one symbol per line and may contain comments beginning with '#'. Leading and trailing whitespace is stripped from each line. May be repeated to read symbols from many files [128] --keep-section=section Keep <section&gt; [129] --keep-symbol=symbol Do not remove symbol <symbol&gt; [130] --keep-symbols=filename Reads a list of symbols from <filename&gt; and runs as if --keep-symbol=<symbol&gt; is set for each one. <filename&gt; contains one symbol per line and may contain comments beginning with '#'. Leading and trailing whitespace is stripped from each line. May be repeated to read symbols from many files [131] --keep-undefined Do not remove undefined symbols [132] -K <value&gt; Alias for --keep-symbol [133] --localize-hidden Mark all symbols that have hidden or internal visibility as local [134] --localize-symbol=symbol [135] Mark <symbol&gt; as local [136] --localize-symbols=filename [137] Reads a list of symbols from <filename&gt; and marks them local [138] -L <value&gt; Alias for --localize-symbol [139] --new-symbol-visibility=<value&gt; [140] Visibility of symbols generated for binary input or added with --add-symbol unless otherwise specified. The default value is 'default' [141] -N <value&gt; Alias for --strip-symbol [142] --only-keep-debug Produce a debug file as the output that only preserves contents of sections useful for debugging purposes [143] --only-section=section Remove all but <section&gt; [144] --output-target=<value&gt; Format of the output file [145] -O <value&gt; Alias for --output-target [146] --pad-to=address Pad the output up to the load address <address&gt;, using a value of zero or the value specified by the --gap-fill option. This option is only supported for ELF input and binary output [147] --prefix-alloc-sections=prefix [148] Add <prefix&gt; to the start of every allocated section name [149] --prefix-symbols=prefix Add <prefix&gt; to the start of every symbol name [150] --preserve-dates Preserve access and modification timestamps [151] -p Alias for --preserve-dates [152] --redefine-sym=old=new Change the name of a symbol old to new [153] --redefine-syms=filename [154] Reads a list of symbol pairs from <filename&gt; and runs as if --redefine-sym=<old&gt;=<new&gt; is set for each one. <filename&gt; contains two symbols per line separated with whitespace and may contain comments beginning with '#'. Leading and trailing whitespace is stripped from each line. May be repeated to read symbols from many files [155] --regex Permit regular expressions in name comparison [156] --remove-section=section [157] Remove <section&gt; [158] --rename-section=old=new[,flag1,...] [159] Renames a section from old to new, optionally with specified flags. Flags supported for GNU compatibility: alloc, load, noload, readonly, exclude, debug, code, data, rom, share, contents, merge, strings, large [160] -R <value&gt; Alias for --remove-section [161] --set-section-alignment=section=align [162] Set alignment for a given section [163] --set-section-flags=section=flag1[,flag2,...] [164] Set section flags for a given section. Flags supported for GNU compatibility: alloc, load, noload, readonly, exclude, debug, code, data, rom, share, contents, merge, strings, large [165] --set-section-type=section=type [166] Set the type of section <section&gt; to the integer <type&gt; [167] --set-start=addr Set the start address to <addr&gt;. Overrides any previous --change-start or --adjust-start values [168] --shared-obj=filename Specify a static shared object file as input for building an mmELF file. [169] --split-dwo=dwo-file Equivalent to extract-dwo on the input file to <dwo-file&gt;, then strip-dwo on the input file [170] --strip-all-gnu Compatible with GNU's --strip-all [171] --strip-all Remove non-allocated sections outside segments. .gnu.warning* and .ARM.attribute sections are not removed [172] --strip-debug Remove all debug sections [173] --strip-dwo Remove all DWARF .dwo sections from file [174] --strip-non-alloc Remove all non-allocated sections outside segments [175] --strip-sections Remove all section headers and all sections not in segments [176] --strip-symbol=symbol Strip <symbol&gt; [177] --strip-symbols=filename [178] Reads a list of symbols from <filename&gt; and removes them [179] --strip-unneeded-symbol=symbol [180] Remove symbol <symbol&gt; if it is not needed by relocations [181] --strip-unneeded-symbols=filename [182] Reads a list of symbols from <filename&gt; and removes them if they are not needed by relocations [183] --strip-unneeded Remove all symbols not needed by relocations [184] --subsystem=name[:version] [185] Set PE subsystem and version [186] -S Alias for --strip-all [187] --target=<value&gt; Format of the input and output file [188] --update-section=name=file [189] Replace the contents of section <name&gt; with contents from a file <file&gt; [190] -U Alias for --disable-deterministic-archives [191] --version Print the version and exit. [192] -V Alias for --version [193] --weaken-symbol=symbol Mark <symbol&gt; as weak [194] --weaken-symbols=filename [195] Reads a list of symbols from <filename&gt; and marks them weak [196] --weaken Mark all global symbols as weak [197] --wildcard Allow wildcard syntax for symbol-related flags. Incompatible with --regex. Allows using '*' to match any number of characters, '?' to match any single character, '' to escape special characters, and '[]' to define character classes. Wildcards beginning with '!' will prevent a match, for example "-N '*' -N '!x'" will strip all symbols except for "x". [198] -W <value&gt; Alias for --weaken-symbol [199] -w Alias for --wildcard [200] -X Alias for --discard-locals [201] -x Alias for --discard-all [202]Pass @FILE as argument to read options from FILE. [203]gmake[1]: Target 'secondary-outputs' not remade because of errors. [204]gmake: *** [makefile:155: all] Error 2 报错
最新发布
07-18
<think&gt;我们正在处理一个TI ARM编译器在OAD(空中下载)构建过程中出现的错误:'No rule to make target 'input-file.error', needed by 'output-file.error''。 这个错误通常发生在make工具尝试构建一个目标时,发现它依赖于另一个文件(或目标),但是makefile中没有规则可以构建那个依赖文件。 根据用户提供的引用,特别是引用[2]中提到了类似的错误:`make: *** No rule to make target `clean'. Stop.`,这通常表示makefile中缺少相应的规则。 解决思路: 1. 确认文件路径名称是否正确:检查`input-file.error`是否存在,或者是否在正确的位置。可能是路径错误或文件缺失。 2. 检查makefile规则:确保makefile中有规则用于生成`input-file.error`。如果没有,需要添加相应的规则。 3. 检查依赖关系:可能`input-file.error`是由其他步骤生成的,确保这些步骤已经执行。 4. 检查文件系统大小写:在Linux下,文件名是大小写敏感的,确保大小写匹配。 5. 如果文件确实不需要,可以尝试从构建规则中移除这个依赖。 另外,考虑到OAD构建可能涉及特定的TI工具链构建脚本,可能需要检查TI提供的构建脚本或示例工程,确认是否有遗漏的步骤。 根据引用[1]中提到的解决缺失库的方法,我们可以联想到,可能是缺少某些必要的组件或工具。但是本错误与文件生成规则相关,因此重点在makefile。 具体步骤: 1. 定位错误:查看完整的错误信息,确定是哪个makefile的哪一行引发了错误。 2. 检查文件是否存在:在错误提示的路径下查找`input-file.error`文件。如果不存在,则需要生成它的规则。 3. 检查生成规则:在makefile中搜索是否有生成`input-file.error`的规则。如果没有,可能需要手动添加规则,或者检查构建脚本是否完整。 4. 检查变量:可能文件路径使用了变量,检查相关变量是否被正确设置。 由于用户没有提供具体的makefile内容,我们只能给出一般性的建议。 如果用户使用的是TI的CCS(Code Composer Studio)或特定的OAD工具链,可能需要检查工程配置,特别是自定义构建步骤。 另外,参考引用[3]中更新工具版本的思路,有时候构建工具版本不匹配也会导致奇怪的错误。可以检查TI编译器、make工具等版本是否符合要求。 总结可能的解决方案: 1. 确保`input-file.error`文件存在,或者有规则生成它。 2. 检查makefile中的规则,特别是生成`input-file.error`的规则是否存在且正确。 3. 更新或重新安装构建工具(如make)TI编译器工具链。 4. 参考TI官方文档或社区,查看是否有类似问题的解决方案。 由于错误信息中提到了具体的文件名(虽然可能是占位符),用户需要根据实际文件名进行替换检查。 生成相关问题: 1. 如何检查makefile中某个目标的生成规则? 2. 在TI ARM编译环境中,如何配置OAD构建步骤? 3. 如何确保构建过程中所有依赖文件都被正确生成? 4. 如何调试makefile的依赖关系?</think&gt;### TI ARM编译器OAD构建错误分析 您在TI ARM编译器环境下进行OAD(Over-the-Air Download)构建时遇到的错误信息`No rule to make target 'input-file.error', needed by 'output-file.error'`是典型的Makefile规则缺失问题。以下是逐步解决方案: #### 1. **检查文件路径大小写** - 确认`input-file.error`在正确路径且文件名完全匹配(Linux系统区分大小写) - 使用`ls -la <文件路径&gt;`验证文件是否存在 - **示例命令**: ```bash find . -name input-file.error # 全目录搜索文件 ``` #### 2. **验证Makefile规则** - 检查Makefile中是否有生成`input-file.error`的规则: ```makefile # 正确规则示例 input-file.error: $(CC) -c $(CFLAGS) -o $@ source-file.c ``` - 若文件是其他工具生成的(如TI编译器脚本),需确保该工具已正确执行 #### 3. **检查依赖顺序** - 在Makefile中确保`output-file.error`的依赖项声明正确: ```makefile output-file.error: input-file.error # 声明依赖关系 $(LD) $(LDFLAGS) -o $@ $^ ``` #### 4. **排除环境配置问题** - 更新TI编译器工具链(可能版本不兼容) - 验证环境变量`CC`、`LD`指向正确的ARM编译器: ```bash echo $CC # 应显示类似 arm-none-eabi-gcc which $(CC) # 检查编译器是否存在 ``` #### 5. **清理并重建项目** - 执行深度清理后重新构建: ```bash make clean # 标准清理 make distclean # 深度清理(如有) make -B # 强制重建所有目标 ``` #### 6. **检查TI OAD工具链** - 确认OAD工具包完整(常见于`<CCS_DIR&gt;/tools/OAD`) - 检查TI文档是否要求额外步骤: - 某些OAD构建需要先执行预处理脚本生成中间文件 - 参考TI官方示例工程(如`ble5_simple_peripheral_oad_offchip`) &gt; ⚠️ **关键提示**:此错误通常由以下原因引起: &gt; 1. 文件被移动或删除(占60%) &gt; 2. Makefile规则错误(占30%) &gt; 3. 工具链路径配置错误(占10%) ### 相关问题 1. 如何调试复杂的Makefile依赖关系? 2. TI OAD构建过程中需要哪些关键配置文件? 3. ARM编译器常见的环境变量配置错误有哪些? 4. 如何验证TI OAD镜像的完整性? &gt; 引用[1]: 在Ubuntu系统解决编译工具链问题需注意32/64位库兼容性[^1]。 &gt; 引用[2]: Makefile规则错误可能导致`No rule to make target`的典型报错[^2]。 &gt; 引用[3]: 工具链版本不匹配可能引发隐蔽的构建错误[^3]。 [^1]: 解决`stubs-32.h`缺失问题需安装兼容库 [^2]: Makefile中`do_configure`阶段失败案例 [^3]: 包管理工具版本不兼容导致构建失败的示例
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值