在JS构造函数中复制属性而不改变原函数可以通过以下几种方式实现:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log("Hello!");
};
function clonePerson(person) {
return Object.assign({}, person);
}
var person1 = new Person("John", 25);
var person2 = clonePerson(person1);
console.log(person2.name); // Output: John
console.log(person2.age); // Output: 25
person2.sayHello(); // Output: Hello!
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log("Hello!");
};
function clonePerson(person) {
return { ...person };
}
var person1 = new Person("John", 25);
var person2 = clonePerson(person1);
console.log(person2.name); // Output: John
console.log(person2.age); // Output: 25
person2.sayHello(); // Output: Hello!
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log("Hello!");
};
function clonePerson(person) {
return Object.create(Object.getPrototypeOf(person), Object.getOwnPropertyDescriptors(person));
}
var person1 = new Person("John", 25);
var person2 = clonePerson(person1);
console.log(person2.name); // Output: John
console.log(person2.age); // Output: 25
person2.sayHello(); // Output: Hello!
以上是在JS构造函数中复制属性而不改变原函数的几种方法,根据具体的需求选择适合的方法即可。
领取专属 10元无门槛券
手把手带您无忧上云