gpt4 book ai didi

javascript - 在javascript中查找属性(property)所有者的姓名

转载 作者:行者123 更新时间:2023-11-28 07:14:15 25 4
gpt4 key购买 nike

我正在关注的一些 javascript 类(class)的示例:

var Tornado = function(name, cities, degree) {
this.name = name;
this.cities = cities;
this.degree = degree;
};

Tornado.prototype = {
nCities: function() {
return this.cities.length
},
valueOf: function() {
return this.nCities() * this.degree;
},
toString: function() {
return this.cities[0][0].toString() + " " + this.name;
}
}

cities = [["Washington", 1], ["Rotterdam", 2]]

var x = new Tornado("crazy", cities, 3)
console.log(x.nCities())
console.log(x.valueOf())
console.log(x + 16)
console.log(x.toString() + "... wow!")


Object.prototype.findOwnerOfProperty = function(propName) {
var currentObject = this;
while(currentObject !== null) {
if(currentObject.hasOwnProperty(propName)) {
return currentObject;
} else {
currentObject = currentObject.__proto__;
}
}
return "No property found!";
};

console.log(x.findOwnerOfProperty("toString"));

findOwnerOfProperty 函数返回定义属性的对象。这很好,但最好也有该对象的名称(本例中为 Tornado.prototype),我该怎么做?

最佳答案

没有内置解决方案。但你可以创建一个属性

this._constructor = arguments.callee.name;

在 Tornado 函数中并创建一个

getConstructor:function(){

return this._constructor;

}

内部原型(prototype)。顺便说一句,忘了说你应该重拍

var Tornado = function

至:

function Tornado

关于javascript - 在javascript中查找属性(property)所有者的姓名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31022837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com