第一次尝试:
function sample() {
sample.show = function() { alert() };
}
这只会在sample
函数并且只有在执行它之后
console.log(sample.show);
//would show undefined on the console
sample();
console.log(sample.show);
//would then show the method definition as it has now been
//defined as a property of "sample"
第二次尝试:
function sample() {
this.show = function() { alert() };
}
仅当您创建示例实例时这才有效
console.log(sample.show);
//will print undefined as there is no property "show" on sample
sample();
console.log(window.show);
//will print the function, but since sample was executed without a
//context, show is created as a property of the global object
//in this case "window"
var d = new sample();
console.log(d.show);
//will print the function as we now have a instance of sample which
//show was made a property of
console.log(sample.prototype.show);
//will show undefined as you are not actually creating the "show" method
//on the constructor sample's prototype
现在有了原型版本:
function sample() {
sample.prototype.show = function() { alert() };
}
有了这个之后,您将能够通过实例或原型链访问“show”方法,但是为了使原型链调用正常工作,您必须至少事先创建一个实例
console.log(sample.prototype.show);
//will print undefined as "show" has not been defined on the prototype yet
var d = new sample();
console.log(d.show);
console.log(sample.prototype.show);
//Both will now print the function because the method has been defined
然而最后一个:
function sample() {
this.prototype.method = function show () { alert() };
}
根本不起作用,因为您无法直接从实例访问原型,一旦尝试创建实例,您将收到未定义的错误。
为了让它工作,你必须通过构造函数链来设置方法
function sample() {
this.constructor.prototype.method = function show () { alert() };
//is the same as doing
sample.prototype.method = function show(){ alert() };
}
所以总的来说,为了让你的“美化”发挥作用,你必须打电话sample
首先,要么直接为第一个,要么为其他创建一个实例。