JavaScript-what is the meaning of [] in the JS function?

Source: Internet
Author: User
function returnfunc (propertyName) {  return function (obj) {             //-----这行定义并返回了一个闭包,也被称之为一个匿名函数    return obj[propertyName];         //这里用方括号法访问属性,因为属性是变量(returnfunc()函数的参数)  };}var savefunc = returnfunc("name");     //调用returnfunc()var result = savefunc({name:"Picasso"});//调用savefunc()alert(result);                        //返回字符串“Picasso”

Name: "Picasso" in Savefunc ({name: "Picasso"})

Reply content:

function returnfunc (propertyName) {  return function (obj) {             //-----这行定义并返回了一个闭包,也被称之为一个匿名函数    return obj[propertyName];         //这里用方括号法访问属性,因为属性是变量(returnfunc()函数的参数)  };}var savefunc = returnfunc("name");     //调用returnfunc()var result = savefunc({name:"Picasso"});//调用savefunc()alert(result);                        //返回字符串“Picasso”

Name: "Picasso" in Savefunc ({name: "Picasso"})

A dot, followed by a [] is a representation of an object's property, except that it contains a string, which is a string.
A variable is generated after the first executionvar propertyName = "name";
And then:

var savrfunc = function(obj){    return obj[propertyName];}

It then executes the above function and returns the return value to result;
The effect on the inside is equivalent to the following:

var obj = {name:"Picasso"};return obj[propertyName]//上面 已经有这个变了 值是name ;所以就是返回了 obj.name ,相当于把 Picasso给返回出去了。

As with the. function, the usage is different

var text ='prop';var obj = {  prop:123};obj.prop//123obj.text//undefinedobj[text]//123

PropertyName is the attribute name, Person[propertyname] is person[' name ']

return obj[propertyName]; //这里用方括号法访问属性,因为属性是变量(returnfunc()函数的请输入代码参数)

It's all in your notes.
The properties of an object are accessed in two ways:

    1. The form of obj.attr, simple writing

    2. OBJ[ATTR], the property name can be the form of a variable

. and [] Both can access the object


Source: JavaScript Standard reference Tutorial (Alpha), by Ruan Yi Feng

  • 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.