Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade For Teachers Spaces Get Certified Upgrade For Teachers Spaces
   ❮     
     ❯   

Basic JavaScript

JS TutorialJS SyntaxJS VariablesJS OperatorsJS If ConditionsJS LoopsJS StringsJS NumbersJS FunctionsJS ObjectsJS DatesJS ArraysJS Typed ArraysJS SetsJS MapsJS MathJS RegExpJS Data TypesJS ErrorsJS EventsJS ProgrammingJS ReferencesJS Versions

JS Advanced

JS FunctionsJS ObjectsJS ClassesJS IterationsJS AsynchronousJS ModulesJS Meta & ProxyJS HTML DOMJS WindowsJS Web APIJS AJAXJS JSONJS jQueryJS GraphicsJS ExamplesJS Reference


JavaScript Meta Programming

Metaprogramming

Metaprogramming refers to a number of ways aprogram can manipulate itself:

  • Modify objects at runtime
  • Inspect objects at runtime
  • Control objects at runtime
  • Intercept running operations
  • Modify functions, and classes
  • Generate dynamic code

The Easy Explanation

Normally,code handles data.

With metaprogramming,code handles code.


Inspecting Objects

With the methodObject.keys() you caninspect object properties.

UsingObject.keys() is a simple example of metaprogramming.

Example

This code is analyzing another piece of code (an object):

// Create an Object
const user = {name: "Jan", age: 40};

// Fill Array with Object keys
const myArr = Object.keys(user);
Try it Yourself »

Modify Objects

I typical metaprogramming task is tomodify object behaviour:

Example

// Create an Object
const person = {name: "John", age: 41};

// Define "name" to return "secret"
Object.defineProperty(person, "name", {
  get() { return "secret"; }
});

let name = person.name;
Try it Yourself »

Generate Dynamic Code

Metaprogramming involves dynamic code generation.

JavaScript cangenerate functions at runtime:

Example

const fn = new Function("a", "b", "return a + b");
Try it Yourself »

Metaprogramming Examples

ConseptDescription
ValidationRestrict the values that can be set to a property
LoggingDisplay property changes using a Proxy
DebuggingIntercept an operation using a Proxy
FrameworksVue, MobX, and Svelte use metaprogramming to detect state changes
ORM / database mappingWrap objects and creates fields based on database schema
Dynamic APIsCreate functions or object structures at runtime

Proxy Metaprogramming

The two objectsProxy andReflect allow for programming at the meta level in JavaScript.

Proxy can be used tointercept property operations like reading or writing.

In the example below:

  • A user object iswrapped in a Proxy
  • The Proxy uses aset() trap to log whenever a property is set

Example

Log changes to property values:

// Create an Object
const user = {name: "Jan", age: 40};

// Wrap the Object in a Proxy
const proxy = new Proxy(user, {
  // Use a set trap
  set(target, property, value) {
    // Log changes
    log(property + "; " + value);
    return target[property];
  }
});

// Change Properties
proxy.name = "John";
proxy.age = 45;
proxy.name = "Paul";
Try it Yourself »

Proxy with Reflect

Reflect makes Proxy behavior match normal object behavior

In the example below:

  • A user object iswrapped in a Proxy
  • The Proxy uses aset() trap to log when a property is set
  • The set trap usesReflect.set() for safe forwarding

Example

Log changes to property values:

// Create an Object
const user = {name: "Jan", age: 40};

// Wrap the Object in a Proxy
const proxy = new Proxy(user, {
  // Use a set trap
  set(target, property, value) {
    // Log changes
    log(property + ": " + value);
    // Safe forwarding with Reflect
    return Reflect.set(target, property, value);
  }
});
Try it Yourself »



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp