function myFunction(messager) {
this.message = messager;
}
new myFunction("Hello");
document.write(myFunction.message);
最佳答案
您试图引用函数对象本身的成员,这是完全不正确的。
当 this
与 new
关键字一起使用时,this
将引用从构造函数隐式返回的对象实例。
这段代码应该可以工作:
function myFunction(messager) {
this.message = messager;
}
var obj = new myFunction("Hello");
document.write(obj.message);
您还可以使用 prototype
成员将成员函数和变量扩充到创建的对象上:
myFunction.prototype.doSomething = function() {
alert('Hello ' + this.message);
}
obj.doSomething(); //alerts "Hello Hello"
关于javascript - 为什么这个 javascript 代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4554152/