【问题标题】:Defining a object's property based onanother object's property根据另一个对象的属性定义一个对象的属性
【发布时间】:2014-03-01 07:27:31
【问题描述】:

我根据来自对象someObjectsomeFunction 定义了一个名为anotherObject 的对象和一个名为anotherFunction 的函数。

 var someObject={
 someFunction:function(){
     return this;
 }
};

console.log(someObject.someFunction()===someObject);//true

var someFunc=someObject.someFunction;
console.log(someFunc===someObject.someFunction);//true
//the function does not have the same context as that of the function called earlier...
console.log(someFunc()===someObject);//false

var anotherObject={
 anotherFunction:someObject.someFunction
};

console.log(anotherObject.anotherFunction===someObject.someFunction);//true
console.log(anotherObject[anotherFunction]()===anotherObject);//true;
console.log(anotherObject.anotherFunction()===someObject);//false

Firefox Scratchpad 报告函数anotherFunction 未定义。

【问题讨论】:

  • (function(){})==(function(){})
  • anotherObject[anotherFunction]() 是垃圾
  • 你的问题到底是什么?
  • 如何将一个对象中的函数复制到另一个对象?

标签: javascript function object


【解决方案1】:

这就是 JavaScript 函数实际工作的方式,someFunction 是一个函数,它的职责是在当前上下文中返回 this,不管这个函数是什么:

var someFunc=someObject.someFunction;

您可以使用 call 来调用它,或者使用您喜欢的任何上下文应用:

var myobj = {};
console.log(someFunc.call(myobj)===myobj);//true
console.log(someFunc.apply(myobj)===myobj);//true

无论您将什么作为callapply 中的第一个参数传递,您的函数都会返回该对象。所以当你看到你的函数做了它应该做的事情,但是如果你希望它总是返回你的第一个对象someObject,你不需要使用this关键字。

阅读my answerHow does JavaScript .prototype work?,我已经尝试在前两部分深入研究这个概念。

这也是您可以找到的有关此概念的最佳资源之一:

Understanding JavaScript Function Invocation and “this”

【讨论】:

  • 我想知道为什么函数someObject.someFunction没有复制到anotherObject.anotherFunction。我对调用和应用有点了解
  • @user2309862:was not copied 是什么意思?当您创建像anotherFunction: someObject.someFunction 这样的函数时,它只会创建对原始函数的引用。
  • 您是说向已传递给更高阶函数的函数添加属性会修改原始函数
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 2018-03-11
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
相关资源
最近更新 更多