在javascript中查找属性所有者的名称

时间:2015-06-24 09:30:49

标签: javascript

我正在关注的一些javascript课程的示例:

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)会更好,我该怎么做?

1 个答案:

答案 0 :(得分:0)

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

this._constructor = arguments.callee.name;

在Tornado函数内部并制作一个

getConstructor:function(){

   return this._constructor;  

}

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

var Tornado = function

为:

function Tornado