[Translation] JavaScript secret garden-hasownproperty, functions, this

Source: Internet
Author: User
Tags hasownproperty
Document directory
  • Conclusion (In conclusion)
  • Named function expression)
  • The global scope)
  • Function call (calling a function)
  • Call a method)
  • Call the constructor)
  • Common pitfalls)
  • Assigning Methods)
  • Javascript garden-original
  • Javascript garden-Chinese Translation
hasOwnProperty

To determine whether an object containsCustomAttribute whileNoFor properties on the prototype chain, we need to use the attributes inherited fromObject.prototypeOfhasOwnPropertyMethod.

Note:Determine whether an attribute isundefinedYesNot enough. Because an attribute may exist, but its value is setundefined.

hasOwnPropertyIs the only processing property in Javascript,NoThe method for searching the prototype chain.

// Modify the object. prototypeobject. prototype. bar = 1; var Foo = {goo: Undefined}; Foo. bar; // 1 'bar' in Foo; // truefoo. hasownproperty ('bar'); // falsefoo. hasownproperty ('goo'); // true

OnlyhasOwnPropertyCorrect and expected results are provided, which is useful when traversing object attributes.NoOther methods can be used to exclude attributes on the prototype chain, rather than defining objects.Itself.

hasOwnPropertyAs a property ( hasOwnPropertyAs a property)

JavascriptNoProtectionhasOwnPropertyIs illegally occupied. Therefore, if an object happens to have this attribute, you must useExternalOfhasOwnPropertyFunction to obtain the correct result.

VaR Foo = {hasownproperty: function () {return false ;}, bar: 'Here be dragons'}; Foo. hasownproperty ('bar'); // always returns false // use hasownproperty of another object and set it to foo {}. hasownproperty. call (Foo, 'bar'); // true
Conclusion (In conclusion)

When you check whether a property exists on an object,hasOwnPropertyYesUniqueAvailable methods. In use at the same timefor inWe recommend that you use loop to traverse objects.AlwaysUsehasOwnPropertyThis will avoid the interference caused by the extension of the prototype object.

Functions)

A function is a first-class object in Javascript, which means that a function can be passed like other values. A common usage isAnonymous FunctionsPassed as the callback function to the asynchronous function.

Function declaration ( functionDeclaration)
function foo() {}

The above method will be parsed (hoisted) before execution, so it exists in the current contextArbitraryIt is correct to call the function definition body.

Foo (); // normal operation, because Foo has been created before the code runs function Foo (){}
Function value expression ( functionExpression)
var foo = function() {};

In this exampleAnonymousFunction assigned to the variablefoo.

Foo; // 'undefined' Foo (); // error: typeerrorvar Foo = function (){};

BecausevarDefines a declaration statement for the variablefooBefore the code is runfooVariables have been defined during code execution.

However, since the value assignment statement is only executed at runtime, before the corresponding code is executed,fooThe default value is undefined.

Named function expression)

Another special case is to assign a name function to a variable.

VaR Foo = function bar () {bar (); // normal operation} bar (); // error: referenceerror

barThe function declaration is invisible because the function has been assigned a value.fooHoweverbarIt is still visible inside. This is caused by JavaScript naming. The function name is in the function.AlwaysVisible.

How this works thisWorks)

Javascript has a setthis. InV.In different cases,thisThe points are different.

The global scope)
this;

When used in all scopesthis, It will pointGlobalObject. (Note: The Javascript script running in the browser. The Global object is window)

Function call (calling a function)
foo();

HerethisWill also pointGlobalObject.

Es5 note:In strict mode, no global variable exists. In this casethisYesundefined. (Note: es5 refers to ecmascript 5, which is the latest JavaScript version released on .)

Call a method)
test.foo();

In this example,thisPointtestObject.

Call the constructor)
new foo();

If the function tends to benewIf the keyword is used together, we call this function a constructor. Inside the function,thisPointNew.

Explicit settings this(Explicit setting this)
Function Foo (a, B, c) {} var bar = {}; Foo. apply (Bar, [1, 2, 3]); // The array will be extended, as shown below Foo. call (Bar, 1, 2, 3); // The parameters passed to foo are: a = 1, B = 2, c = 3

When usingFunction.prototypeOncallOrapplyMethodthisWill beExplicit settingsIs the first parameter of the function call.

ThereforeFunction callIn the preceding examplefooFunctionthisSetbar.

Note:In the literal declaration Syntax of an object,this NoIt is used to point to the object itself. Thereforevar obj = {me: this}InmeNot pointingobjBecausethisIt may only appear in the preceding five cases. (Note: In this example, if you are running in a browser, obj. Me equals to the window object .)

Common pitfalls)

Although most of the cases are mentioned in the past, the first rule (note: this should be the second rule, that is, when a function is called directly,thisPoint to the Global Object) is considered another wrong design place In the Javascript language, because itAlwaysThere is no actual purpose.

Foo. method = function () {function test () {// This will be set as a global object (in the browser environment, it is also a window object)} test ();}

A common misunderstanding is thattestInthisWill pointFooObject, in factNoThis way.

TotestTo obtainFooObject reference, we needmethodCreate a local variable pointingFooObject.

Foo. method = function () {var that = This; function test () {// use that to point to the foo object} test ();}

thatIt's just a casual name, but this name is widely used to point to externalthisObject. In the closures section, we can see thatthatIt can be passed as a parameter.

Assigning Methods)

Another strange thing is the function alias, that is, a methodAssignmentTo a variable.

var test = someObject.methodTest;test();

In the above example,testAs a normal function is calledthisWill not be directedsomeObjectObject.

AlthoughthisThe late binding feature of does not seem friendly, but it is based on the soil on which prototype inheritance depends.

function Foo() {}Foo.prototype.method = function() {};function Bar() {}Bar.prototype = Foo.prototype;new Bar().method();

WhenmethodWhen called,thisWill pointBarInstance Object.

This Chinese translation is original on sanshangshi, and is the first in the blog Park. For more information, see the source.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.