简体   繁体   English

如何从函数内部为全局函数分配属性

[英]How to assign a property to a global function from inside that function

Assuming functions in javascript are actually objects, how can I assign properties to this function object within the function itself. 假设javascript中的函数实际上是对象,那么如何在函数本身内为该函数对象分配属性。

Below are not working as 'this' keyword is referring to the window object, so 'prop' will be assigned to the window global object not to the function object. 由于'this'关键字是指窗口对象,因此下面的命令不起作用,因此'prop'将分配给窗口全局对象而不是函数对象。

function test() {
    this.prop = value;
}

Why 'this' keyword inside global functions is referring to the window object and not referring to the function object itself? 为什么全局函数中的'this'关键字是指窗口对象而不是函数对象本身?

Edit: 编辑:

My question is different from the duplicate question as I am asking how to assign a property to a global function inside that function, not about the scope of variables. 我的问题与重复问题不同,因为我要问的是如何向该函数内部的全局函数分配属性,而不是变量的范围。

Reference the function by name: 通过名称引用该函数:

 function test(value) { test.prop = value; } test('hello'); console.log(test.prop); // => "hello" 

Short answer: invoke the function via call and pass the intended this as the first argument. 答案很简单:通过调用函数call ,并通过预期this作为第一个参数。

function test(value) {
  this.prop = value
}

//  'this' v     v value
test.call(test, 10)
console.log(test.prop) // 10

The purpose of call is to explicitly set the this of the invoked function. call的目的是显式设置被调用函数的this

Explanation: 说明:

For non-strict mode, when the function is invoked without a caller, eg, test(10) , this is implicitly set to the global object, in this case window . 对于非严格模式中,当函数时没有呼叫者调用,例如, test(10) this是隐式设置为全局对象,在这种情况下window In strict mode, it will be undefined . 在严格模式下,它将是undefined

function test() {
  return this
}

console.log(test()) // window (or undefined in strict mode)

Inside of a function, this refers to the caller of the function. 在函数内部, this是指函数的调用者。

const caller = {
    test: function () { return this }
}

console.log(caller.test()) // caller, i.e., { test: function() {...} }

This is true with 'classes' as well (functions invoked with new ). “类”也是如此(用new调用的函数)。

function MyConstructor() {
  this.test = function() {
    return this
  }
}

const instance = new MyConstructor()
console.log(instance.test()) // instance of MyConstructor

Depending on your use case, it may be preferable to use this form: 根据您的用例,最好使用以下形式:

const myObj = {
  test: function(value) {
    this.prop = value
  }
}

// 'prop' will be set on `myObj` instead of the function.
myObj.test(10)
console.log(myObj) // { prop: 10, test: function(value) {...} }

or a class-like construct: 或类似类的构造:

function MyConstructor(value) {
  this.prop = value
}

const instance = new MyConstructor(10)
console.log(instance) // MyConstructor { prop: 10 }
console.log(instance.prop) // 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM