我尝试创建一个像 jQuery 一样的动态原型(prototype)并且能够函数链,但是我在没有使用 new 和函数内部时出错,返回 this
对象正确吗?
(function() {
var peopleDynamicProto = function(name, age, state) {
this.name = name;
this.age = age;
this.state = state;
if (typeof this.printPerson !== 'function') {
peopleDynamicProto.prototype.printPerson = function() {
console.log(this.name + ',' + this.age + ',' + this.state);
return this;
};
}
if (!this.hasOwnProperty('gender')) {
peopleDynamicProto.prototype.gender = 'male';
return this;
}
}
window.peopleDynamicProto = peopleDynamicProto;
return peopleDynamicProto;
})();
//var person1 = new peopleDynamicProto('john', 23,'CA');
//person1.printPerson();
peopleDynamicProto('john', 23, 'CA').printPerson(); //got error
谁知道问题出在哪里?
最佳答案
如果你想创建一个基于原型(prototype)的新对象,你必须使用“new”。
我不确定您到底要做什么,以及为什么要尝试动态创建原型(prototype)。我不会说 100% 肯定,但我不认为 jQuery 会那样做(而且这看起来是一种非常糟糕的做法)。
如果你想做一些像 jQuery 这样的事情,你的类是可链接的并且可以链接为 (new peopleDynamicProto(...)).print()
或 peopleDynamicProto(... ).print()
,那么你可以这样做:
function peopleDynamicProto(name) {
if (this instanceof peopleDynamicProto) {
/* initialize attributes here */
this.name = name;
} else {
return new peopleDynamicProto(name);
}
}
peopleDynamicProto.prototype.printPerson = function() {
console.log( this.name );
return this;
}
现在你应该可以用两种方式调用它了:
peopleDynamicProto('john').printPerson();
(new peopleDynamicProto('john')).printPerson();
如果你不关心支持这两种方式,那么你可以只返回一个对象,例如:
function peopleDynamicProto(name) {
return {
name: name,
printPerson = function() {
console.log( this.name );
return this;
}
};
}
peopleDynamicProto('John').printPerson();
(还有其他方法)
关于javascript - 创建类似 jquery 函数链的动态原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41318453/