下面的代码运行正常:原型函数没有定义
function Button(tagName) {
var button;
if (tagName) button = document.createElement(tagName);
else button = document.createElement(div);
button.innerHTML = 'Track Order';
button.applyJsonProperties = function(jsonProperties){
if(jsonProperties){
for(var cssAttribute in jsonProperties){
this.style[cssAttribute] = jsonProperties[cssAttribute];
}
}
}
return button;
}
下面的代码产生错误
function Button(tagName) {
var button;
if (tagName) button = document.createElement(tagName);
else button = document.createElement(div);
button.innerHTML = 'Track Order';
return button;
}
Button.prototype.applyJsonProperties = function(jsonProperties){
if(jsonProperties){
for(var cssAttribute in jsonProperties){
this.style[cssAttribute] = jsonProperties[cssAttribute];
}
}
}
var divButton = new Button('div');
var props = { "color" : "blue" }
divButton.applyJsonProperties(props); //returns undefined function
'divButton.applyjSonProperties(道具)'错方法名 –
对象从返回*作为构造函数调用的Button *函数不是* Button *的实例,即它不会继承* Button.prototype *,因为它返回一个DOM Bu tton元素,而不是构造函数的* this *。 – RobG
您在这里错过了'div'的引号:'document.createElement(div)'。你可以将代码简化为'tagName = tagName || 'div';'在第一行。 – Barmar