【问题标题】:Assigning a property to arrow function?将属性分配给箭头函数?
【发布时间】:2019-10-11 12:10:55
【问题描述】:
import React from "react";
import PropTypes from "prop-types";

const Component = ({ children }) => <div>{children}</div>;

Component.propTypes = { children: PropTypes.object }; //what is not clear

它有效。但为什么它会起作用?由于我正在使用 JavaScript,因此我以前从未遇到过这种情况。出于好奇,我试过这个:

const fn = () => {};

fn.prop = true;

console.log(fn, fn(), "it seems like prop is not assigned");

//just to clarify for those who don't understand the question:

const obj = {};

obj.prop = true;

console.log(obj, "prop assigned to the object. fine.");

const secondFn = () => ({});

const objFromSecondFn = secondFn();

objFromSecondFn.prop = true;

console.log(objFromSecondFn, "prop assigned to the object. clear.");

console.log("comparison:", fn, obj, objFromSecondFn);

但它似乎没有做任何事情。那么这种方法可以解决什么问题,以及背后发生了什么?

【问题讨论】:

  • 你认为它应该怎么做?
  • 你的问题不清楚。特别是你的第二个例子。
  • 函数是对象,因此您可以像使用对象一样向它们添加属性
  • (这两个代码sn-ps有什么关系?)
  • "好像没有分配 props" - 是的,但它被分配给 fn 而不是 fn()。并且根据您的控制台实现,它在记录函数时仅显示函数代码,而不是其属性。但是当您使用console.log(fn.prop, "the property itself") 时,它就会出现。

标签: javascript


【解决方案1】:

函数是对象,但添加到函数的属性不会传递到它们返回的对象(除非在构造函数中使用原型)

const fn = () => {};
fn.prop = true;
console.log(fn.prop) // is actually set, but fn().prop is not

在您的 React 示例中,您创建的 Component 函数由库代码使用,无需运行该函数即可读取 Component.propTypes 以强制执行类型。因此,您只是创建了一个可调用函数并附加了一些相关数据 - 创建了一个可以在其他地方使用的接口。

【讨论】:

    【解决方案2】:

    这是 es6 中引入的 destructuring 语法。您可以在其中解压缩作为函数参数传递的对象的字段。 Example 从链接文档中提取:

    var user = {
      id: 42,
      displayName: 'jdoe',
      fullName: {
        firstName: 'John',
        lastName: 'Doe'
      }
    };
    
    function userId({id}) {
      return id;
    }
    
    function whois({displayName, fullName: {firstName: name}}) {
      return `${displayName} is ${name}`;
    }
    
    console.log(userId(user)); // 42
    console.log(whois(user));  // "jdoe is John"
    

    我希望这个例子能让您了解幕后发生的事情。如果你想进一步学习,我建议你关注my other answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 2016-01-15
      • 2018-06-28
      • 2022-12-14
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多