简体   繁体   中英

Can someone please explain why document[“write”] works?

I was helping to de-obfuscate a javascript snippet today, and was surprised to find this:

document["write"]('obfuscated code here');

The word "write" was also obfuscated, making it slightly harder to understand the code's intent.

I've never seen document treated as an array before, and I'm curious how/why this works. Are there other functions that can be called in a similar manner?

document is a Javascript object (not an array). Object fields can be accessed by dot ( parent.child ) or subscript ( parent['child'] ) syntax.

You can try it yourself:

var myObject = {
  field: 'hello!'
}

console.log(myObject['field']);
console.log(myObject.field);

The subscript syntax is useful when you have a field name that is not a valid Javascript identifier:

var myObject = {
  'my-field': 'hello!'
}

console.log(myObject['my-field']);     // Works as expected
console.log(myObject.my-field);        // ReferenceError
console.log(myObject.'my-field');      // SyntaxError

See the MDN docs on property accessors .

Because you can access object keys as ['key'] as well as .key . "Classes" in javascript are just objects.

Consider the following:

var foo = {
    bar: function() {
        alert('We are here!');
    }
};

foo.bar(); //The bar key of the object accessed using .key
foo['bar'](); //The bar key of the object accessed using ['key']

Because document is an object in javascript, a DOM object. And in javascript its possible to access properties by using either object.property or object['property']

So you can write it as

document.write(...);

OR

document['write'](...);

There are two types of notation: dot ( . ) and array( [] ) when dealing with objects. Both will access the property named after the dot or in the index

So if you have something like

var obj = {
  someproperty:"something",
  somefunction:function(){}
};

Both obj.someproperty and obj["someproperty"] reference the object's property with that name.

This of course will also work on arrays, except you cannot use dot notation to access the elements, as arrays are just objects.

var arr = [2,1,3];
console.log(arr[1])
arr["sort"]();
console.log(arr)

However you cannot access the array's elements through dot notation

arr.1

will throw an error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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