Home >Web Front-end >JS Tutorial >Parsing invisible data types in JavaScript_javascript tips

Parsing invisible data types in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:11:181005browse

JS provides some built-in objects, functions and constructors for us to program, such as Math, parseInt, Object, Array, etc. These are all visible and can be used during programming. For example, I can use new Object or new Array.

Some are invisible, and these objects can only be provided by the engine in special circumstances. These types of objects often have reduced functionality. Here are some

1. Arguments type
Arguments type cannot be created manually by programmers, that is, you cannot new Arguments(). It has and only one object arguments

Copy code The code is as follows:

function func() {
console.log(arguments[0]) // 1
console.log(arguments.length) // 3
}
func(1, 2, 3)

The arguments object is created when the function is called and is only visible and used inside the function. You can see that arguments are very similar to Array, elements can be retrieved by index, and they also have a length attribute. But it is not Array. It does not have some methods of Array such as push, pop, etc. Arguments are defined in ES5 10.6.

2. The function returned by bind is very special
bind is a new method added to Function.prototype by ES5. It is called directly on function like call/apply. It returns a function with specified context and parameters.

Copy code The code is as follows:

function func(age) {
console.log ('name: ' this.name ', career: ' age)
}
var person = {name: 'John McCarthy'}
var f1 = func.bind(person, 'computer scientist')
f1() // name: John McCarthy, career: computer scientist

You can see that the returned function f1 is called using parentheses like a normal function. Everything works fine, but the following code will surprise you
Copy the code The code is as follows:

function func(age) {
console.log('name: ' this.name ', career: ' age)
}
var person = {name: 'John McCarthy'}
var f1 = func.bind(person, 'computer scientist')
console.log(f1.prototype) // undefined

Compared with the above code, the last sentence is different, f1() is not executed , but printed out f1.prototype and found it to be undefined.

Is it weird? Doesn't every function have a prototype attribute? This is used to implement prototype inheritance. Indeed, the function returned by bind is special, it does not have a prototype. This special function is created by the JS engine and cannot be directly measured by the client programmer through function declaration or function.

This is clearly stated in the specification ES5 15.3.4.5

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn