위의 의견에서 ugliness of dynamically-named functions에 대한 블로그 게시물을 이미 연결했습니다.
어쨌든 JavaScript는 입력 된 언어가 아니므로 다른 언어의 숙어를 가져 와서는 안됩니다.
은 정말 당신이 여기 힘겨운 싸움을하고 있다고 생각하지만, 여기에 내가
struct.js
function Struct(obj, props) {
for (var name in props) {
if (props.hasOwnProperty(name)) {
this[name] = obj[name];
}
}
this.meta = props;
}
// you could add Struct.prototype methods here if you wanted
// Struct.prototype.foo = function foo() { ... }
person.js
var person = require("./struct");
function Person(obj) {
// idempotent
if (obj instanceof Person) {
return obj;
}
// optional `new`
if (!(this instanceof Person)) {
return new Person(obj);
}
// call Struct constructor with context of `this` (Person instance)
Struct.call(this, obj, {
name: String,
surname: String
});
}
// if you want to attach to the Struct prototype, uncomment this
// Person.prototype = Object.create(Struct.prototype, {
// constructor: {
// value: Person
// }
// });
해낸 일이다
사용법
귀하의 코멘트
에 대해서는210
var person = new Person({surname: 'Canti', name: 'Giulio'});
console.log(person.constructor.name, person);
출력
Person {
name: 'Giulio',
surname: 'Canti',
meta: {
name: [Function: String],
surname: [Function: String]
}
}
링크 주셔서 감사합니다. 나에 대한 몇 가지 문제를 분명히했지만, 나는 어둠 속에서 여전히 비틀 거리고있다. 함수가 .name 특성을 가질 수 있다면 변경 될 수 있다고 생각했을 것입니다.
나는 당신의 생각 과정을 여기에서 이해하지만 당신은 객체 property descriptors에 대해 알고 있어야합니다. 모든 속성이 동일한 방식으로 작동하는 것은 아닙니다. Person.constructor.name
속성이 writable
또는 confirgurable
아니라고
이
function Person(name) { this.name = name; }
Object.getOwnPropertyDescriptor(Person.constructor, "name");
// Object {value: "Function", writable: false, enumerable: false, configurable: false}
var p = new Person("naomik");
Object.getOwnPropertyDescriptor(p, "name");
// Object {value: "naomik", writable: true, enumerable: true, configurable: true}
공지 사항에서보세요.
여기서 말하는 이름은 객체의 생성자입니다. 물론 당신은 그것을 바꿀 수 있지만 그것이 정말로 원하는 것입니까? 이름뿐 아니라 적절한 의미 체계에 관한 것입니다. –
보시다시피, 동적 이름을 사용하여 함수를 만드는 것은 정말 못 생기고 정말 빠른 http : // marcosc가됩니다.com/2012/03/dynamic-function-names-in-javascript/ – naomik
당신은 어떤 언어를 사용하고 있으며 실제로 무엇을 성취하려고합니까? – naomik