访问器属性及其功能名称

时间:2017-01-26 03:38:47

标签: javascript function ecmascript-6 getter

ECMAScript 6中的所有函数都具有适合其name属性的值。那些访问者属性(getter和setter)的名称呢?

示例(来自Understanding ECMAScript 6书籍):

class FriendModel {
    var index = ""
    var thumbnail = ""
    var name = ""
}

let fm0 = FriendModel()
fm0.index = "100"
fm0.thumbnail = "tell.png"
fm0.name = "Phillips"

let fm1 = FriendModel()
fm1.index = "200"
fm1.thumbnail = "ask.png"
fm1.name = "Allen"

var array = [FriendModel]()
array.append(fm0)
array.append(fm1)

// The index below is an index of the array. Do not confuse with the FriendModel.index
let index = array.index {
    return $0.thumbnail == "ask.png" && $0.name == "Allen"
}
array.forEach { print($0.name) }

print("Array index:", index ?? "n/a")

array.remove(at: index!)

array.forEach { print($0.name) }

您能解释为什么var doSomething = function doSomethingElse() { // empty }; var person = { get firstName() { return "Nicholas" }, sayName: function() { console.log(this.name); } } console.log(doSomething.name); // "doSomethingElse" console.log(person.sayName.name); // "sayName" console.log(person.firstName.name); // undefined, instead of "get firstName" 会返回person.firstName.name吗?

4 个答案:

答案 0 :(得分:2)

因为person.firstName === "Nicholas""Nicholas".name不存在。

使用getter时,您直接访问实际返回的值,只要执行它的行理解,您就不会调用函数,它与尝试:

var obj = { something: 'someValue' };
console.log(obj.something.name);

也将返回undefined。

答案 1 :(得分:2)

由于person.firstName是一个getter,返回值是getter返回的任何内容(在您的示例中为"Nicholas"),而不是getter函数本身,因此您无法以这种方式访问​​其名称。

为了获得对该功能的引用,您可以使用Object.getOwnPropertyDescriptor

var person = { 
    get firstName() {
        return "Nicholas"
    },
}

var descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');

console.log(descriptor);
console.log(descriptor.get.name);

答案 2 :(得分:1)

因为person.firstName是返回值的类型,所以string和字符串没有属性.name

person.saynamedoSomethingElse是函数,并且具有.name属性

console.log(typeof doSomething); // function
console.log(typeof person.sayName); // function
console.log(typeof person.firstName); // string

答案 3 :(得分:0)

我认为这是因为属性name仅适用于函数,而不适用于变量

如果你有代码:

let var1 = "non function";
let var2 = {};
let var3 = function(){};
let var4 = function hello(){};
let var5 = class AClass{};

console.log(var1.name); // undefined
console.log(var2.name); // undefined
console.log(var3.name); // var3
console.log(var4.name); // hello
console.log(var5.name); // AClass

您可以看到var1var2不是函数或类,而是其他函数或属性name