对Javascript构造函数和原型感到困惑
所以我试图构建一个自定义的构造函数来使用,我对原型部分有点困惑。我正在测试它,当我去做一个console.log(testVar.getHostname)时;它以文本形式返回函数 所以我有以下几点对Javascript构造函数和原型感到困惑,javascript,Javascript,所以我试图构建一个自定义的构造函数来使用,我对原型部分有点困惑。我正在测试它,当我去做一个console.log(testVar.getHostname)时;它以文本形式返回函数 所以我有以下几点 function nodeInfo(hostname) { this.hostname = hostname; }; nodeInfo.prototype.getHostname = function() { return this.hostname; }; var testVar
function nodeInfo(hostname) {
this.hostname = hostname;
};
nodeInfo.prototype.getHostname = function() {
return this.hostname;
};
var testVar = new nodeInfo("google.com");
console.log(testVar.getHostname);
function () {
return this.hostname;
}
输出如下
function nodeInfo(hostname) {
this.hostname = hostname;
};
nodeInfo.prototype.getHostname = function() {
return this.hostname;
};
var testVar = new nodeInfo("google.com");
console.log(testVar.getHostname);
function () {
return this.hostname;
}
知道我做错了什么吗?原型方法可以在构造函数之外吗?我在谷歌搜索的一堆文章中看到过这种情况。
比如
非常感谢您的帮助。您需要console.log(testVar.getHostName())
来运行该函数
JavaScript中的函数是一级值。它们可以被变量引用、存储在数组中、设置为属性等。在本例中,您要求它为函数打印一个字符串值,这恰好是本例中的源代码。你也可以这样做:
console.log( typeof testVar.getHostName );
// "function"
为了提高您的知识水平,请检查并思考以下内容:
var testVar = new nodeInfo("google.com");
hostName = "Global";
var f1 = testVar.getHostName;
var o = { f2: testVar.getHostName, hostName:"In Object" };
console.log( testVar.getHostName() );
console.log( f1() );
console.log( o.f2() );
f1.call( o );
o.f2.call( testVar );
没错
testVar.getHostname
是一个函数。你试过叫它吗<代码>控制台.log(testVar.getHostname())代码>