JavaScript中object.method()与object.method的区别及style语法疑问
element.style.display in JavaScript Great question—this is a super common point of confusion when starting out with JS and DOM manipulation, so let’s clear it up!
First, let’s correct your initial assumption: style is not a method, it’s a property of DOM elements. Here’s the step-by-step breakdown:
- When you run
document.querySelector('dice'), you get back a DOM element object (like a<div>or whatever yourdiceelement is). - This element object has a built-in
styleproperty that directly gives you access to aCSSStyleDeclarationobject. This object holds all the inline CSS styles applied to the element. - Since
styleis a property, you don’t need parentheses to access it—you just use dot notation (element.style) to get the style object, then modify itsdisplayproperty to'none'to hide the element.
To make this distinction even clearer, think about how properties and methods work in JavaScript:
- Methods are functions attached to objects, so you need parentheses to execute them (like
document.querySelector()—notice the parentheses here, because it’s a method that runs and returns an element). - Properties are values (or nested objects) attached to objects, which you access directly without parentheses. For example:
const car = { color: "blue", // This is a property honk() { // This is a method console.log("Beep!"); } }; console.log(car.color); // Accessing a property—no parentheses needed car.honk(); // Calling a method—requires parentheses to run
One quick side note: If you’ve seen something like getComputedStyle(element).display, that uses a method (getComputedStyle() needs parentheses) because it’s a function that calculates and returns the final applied styles for an element. But element.style is specifically for accessing or setting inline styles directly, so it’s a property, not a method.
So to recap: Your original code document.querySelector('dice').style.display='none' works because style is a property, not a method—no parentheses required!
内容的提问来源于stack exchange,提问作者Kshitij Kohli

