2014-04-09 63 views
1

如何通过名称空间获取实例化对象的类型名称?如何在JavaScript中获取此对象的类型名称?

考虑宣布的传承的这两种方式:

模块

通过这种方式之外,还有名为Shark一个function对象,因此每当我问myShark.constructor.name,它返回名称constructor引用的功能,即Shark

// Fish 
function Fish() { 
    this.fins; 
} 
Fish.prototype.swim = function() { 
    console.log("Swim"); 
}; 

// Shark 
function Shark() { 
    this.teeth; 
} 
Shark.prototype = new Fish; 
Shark.prototype.constructor = Shark; 

var myShark = new Shark(); 
console.log("My shark is: " + myShark.constructor.name); 
// Prints => My shark is: Shark 

里面一个模块

这是所有罚款,但每当我宣布一个模块内部的继承结构,我通常如下构建它。问题在于Yacht的构造函数引用了一个匿名函数。因此,每当我要求myBoat.constructor.name它有一个空字符串。有没有办法让我仍然可以获得对象类型的String表示形式?

var boats = (function() { 
    exports = {}; 

    // Boat 
    exports.Boat = function() { 
     this.crew = 1; 
    }; 
    exports.Boat.prototype.sail = function() { 
     console.log("Sail"); 
    }; 

    // Yacht 
    exports.Yacht = function() { 
     this.decks = 4; 
    }; 
    exports.Yacht.prototype = new exports.Boat; 
    exports.Yacht.prototype.constructor = exports.Yacht; 

    return exports; 
}()); 

var myYacht = new boats.Yacht(); 
console.log("My boat is: " + myYacht.constructor.name); 
// Prints => My boat is: 

我已经考虑改变我如何声明继承,以便创建一个名为模块内部的功能,然后通过exports暴露它们如下。有没有其他方法可以得到相同的结果而不需要必须作出命名的功能,然后将它们附加到出口?

var drinks = (function() { 
    var exports = {}; 

    // Drink 
    function Drink() { 
     this.calories = 130; 
    } 

    // Beer 
    function Beer() { 
     this.alcohol = 8; 
    } 
    Beer.prototype = new Drink; 
    Beer.prototype.constructor = Beer; 

    exports.Drink = Drink; 
    exports.Beer = Beer; 

    return exports; 
}()); 

var myBeer = new drinks.Beer(); 
console.log("My drink is: " + myBeer.constructor.name); 
// Prints => My drink is: Beer 

回答

1

另一种方法是使用函数表达式的名称:

// Yacht 
exports.Yacht = function Yacht() { 
    this.decks = 4; 
}; 
exports.Yacht.prototype = new exports.Boat; 
exports.Yacht.prototype.constructor = exports.Yacht; 
// incorrect: exports.Yacht.prototype.constructor = Yacht 
// as the name is not in the scope 

// ... 
var myYacht = new boats.Yacht(); 
console.log("My boat is: " + myYacht.constructor.name); 
// My boat is: Yacht 

注意添加名字到功能将不会引入Yacht进入主功能的范围,所以它不一样的功能在第三个代码片段中使用的声明方法。此外,它更简洁。 )

+0

当你说“主要功能的作用域”时,你的意思是命名空间/模块的权利?这样做有没有其他副作用?如果没有,我可能会采取这条路线。 – zero298

+0

是的,模块功能;没有我知道的。 ) – raina77ow