Is it possible to automatically stringify in JavaScript?
I know I can create a toString()
function on an object, so that every time it's printed or treated like a string it will first stringify the object with that function.
Is it possible to do that directly so I can use String object functions on the object?
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
}
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // This that
console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split()) // Error
Is it possible to do so that the object "behaves" like a string when a String function is called on it?
In other words, I'd like objInstance.split()
to have the same result as ("" + objInstance).split('')
, and also objInstance.length
or objInstance.match(/something/)
, etc.
javascript
add a comment |
I know I can create a toString()
function on an object, so that every time it's printed or treated like a string it will first stringify the object with that function.
Is it possible to do that directly so I can use String object functions on the object?
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
}
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // This that
console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split()) // Error
Is it possible to do so that the object "behaves" like a string when a String function is called on it?
In other words, I'd like objInstance.split()
to have the same result as ("" + objInstance).split('')
, and also objInstance.length
or objInstance.match(/something/)
, etc.
javascript
So you want to be able to concatenate all values of an object and search through it. You're doing it for searching purpose right ?
– Walfrat
Dec 17 at 12:36
1
Just curious, what are you trying to do with this?
– Addison
Dec 17 at 16:40
add a comment |
I know I can create a toString()
function on an object, so that every time it's printed or treated like a string it will first stringify the object with that function.
Is it possible to do that directly so I can use String object functions on the object?
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
}
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // This that
console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split()) // Error
Is it possible to do so that the object "behaves" like a string when a String function is called on it?
In other words, I'd like objInstance.split()
to have the same result as ("" + objInstance).split('')
, and also objInstance.length
or objInstance.match(/something/)
, etc.
javascript
I know I can create a toString()
function on an object, so that every time it's printed or treated like a string it will first stringify the object with that function.
Is it possible to do that directly so I can use String object functions on the object?
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
}
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // This that
console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split()) // Error
Is it possible to do so that the object "behaves" like a string when a String function is called on it?
In other words, I'd like objInstance.split()
to have the same result as ("" + objInstance).split('')
, and also objInstance.length
or objInstance.match(/something/)
, etc.
javascript
javascript
edited Dec 17 at 21:27
Peter Mortensen
13.5k1983111
13.5k1983111
asked Dec 17 at 6:30
simone
1,43511426
1,43511426
So you want to be able to concatenate all values of an object and search through it. You're doing it for searching purpose right ?
– Walfrat
Dec 17 at 12:36
1
Just curious, what are you trying to do with this?
– Addison
Dec 17 at 16:40
add a comment |
So you want to be able to concatenate all values of an object and search through it. You're doing it for searching purpose right ?
– Walfrat
Dec 17 at 12:36
1
Just curious, what are you trying to do with this?
– Addison
Dec 17 at 16:40
So you want to be able to concatenate all values of an object and search through it. You're doing it for searching purpose right ?
– Walfrat
Dec 17 at 12:36
So you want to be able to concatenate all values of an object and search through it. You're doing it for searching purpose right ?
– Walfrat
Dec 17 at 12:36
1
1
Just curious, what are you trying to do with this?
– Addison
Dec 17 at 16:40
Just curious, what are you trying to do with this?
– Addison
Dec 17 at 16:40
add a comment |
3 Answers
3
active
oldest
votes
You can let your objects inherit from String
so that all string methods become available:
class SomeObject extends String {
constructor(a, b) {
super(a + " " + b);
this.a = a;
this.b = b;
}
}
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
No need to use complicated Proxy
solutions :-)
All the String.prototype
methods (except for .toString
, .valueOf
and [Symbol.iterator]
) are "intentionally generic; [they do] not require that its this
value be a String
object. Therefore, [they] can be transferred to other kinds of objects for use as a method." You can call them on any value, they will coerce it to a string (using .toString()
or .valueOf
as usual).
You don't even need to use ES6 class extends
to inherit from the builtin (which also makes your string value immutable), it works in ES5 as well:
function SomeObject(a, b) {
this.a = a;
this.b = b;
}
SomeObject.prototype = Object.create(String.prototype);
SomeObject.prototype.constructor = SomeObject;
SomeObject.prototype.toString = function() {
return this.a + " " + this.b;
};
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
5
Is this considered good practice? It seems like a misuse of inheritance.
– usr
Dec 17 at 18:48
2
@usr Maybe it is, I don't know the OPs use case. However, if they want all ofString
s methods on their custom instances, that sounds quite a bit like subtyping.
– Bergi
Dec 17 at 18:52
add a comment |
One option would be to return a Proxy
that checks whether the property exists on String.prototype
, and if it does, calls that property with the string that represents the object:
// Declare the proxy handler up front here
// to avoid unnecessary creation of duplicate handler objects
const handler = {
get(obj, prop) {
if (obj[prop] !== undefined) {
return obj[prop];
}
const stringMethod = String.prototype[prop];
if (stringMethod) {
return stringMethod.bind(obj.a + ' ' + obj.b);
}
},
};
const SomeClass = function(a, b) {
this.a = a;
this.b = b
return new Proxy(this, handler);
}
const instance = new SomeClass('this', 'that');
// String methods:
console.log(instance.trim());
console.log(instance.includes('this'));
console.log(instance.includes('somethingelse'));
console.log(instance.split(''));
// Can still assign and retrieve values directly on the object as normal:
instance.foo = 'foo';
console.log(instance.foo);
This options is really good, +1
– Just code
Dec 17 at 6:49
2
+1. Remark: this definition is only available in ecmascript 6 or later. Reference
– devildelta
Dec 17 at 6:51
3
I would recommend to declare the handler object outside of the constructor function, for the same reason that you should define methods on the prototype. Then you'd also use thetarget
argument instead of closing overthis
.
– Bergi
Dec 17 at 9:30
add a comment |
One option to extend the SomeObject
too, something like this.
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
SomeObject.prototype.split = function() {
return String.prototype.split.apply(this.toString(), arguments);
};
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
In a comment you've asked:
I was thinking about doing this programmatically by doing it for all functions - but is there a way to list all functions of an object?
Yes, you'd use getOwnPropertyNames
on String.prototype
and filter out the ones that aren't functions:
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
Object.getOwnPropertyNames(String.prototype).forEach(function(name) {
var fn = String.prototype[name];
if (name !== "toString" && typeof fn === "function") {
SomeObject.prototype[name] = function() {
return fn.apply(this.toString(), arguments);
};
}
});
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
Interesting thought. I was thinking about doing this programmatically by doing it for all functions - but is there a way to lost all functions of an object?
– simone
Dec 17 at 6:51
@simonelost all functions of an object
you mean? Do it only if you have custom requirements, doesn't makes sense if you do it for all the functions.
– Just code
Dec 17 at 6:54
"lost" should have been "list" - list all functions of an object
– simone
Dec 17 at 7:02
@simone to handle all the functions of an object, you can use certainperformance's solution.
– Just code
Dec 17 at 7:03
I was wondering about performance in using Proxy. Same as in setting the prototype in a deleted solution. But both look quite interesting...
– simone
Dec 17 at 7:04
|
show 2 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53809965%2fis-it-possible-to-automatically-stringify-in-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can let your objects inherit from String
so that all string methods become available:
class SomeObject extends String {
constructor(a, b) {
super(a + " " + b);
this.a = a;
this.b = b;
}
}
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
No need to use complicated Proxy
solutions :-)
All the String.prototype
methods (except for .toString
, .valueOf
and [Symbol.iterator]
) are "intentionally generic; [they do] not require that its this
value be a String
object. Therefore, [they] can be transferred to other kinds of objects for use as a method." You can call them on any value, they will coerce it to a string (using .toString()
or .valueOf
as usual).
You don't even need to use ES6 class extends
to inherit from the builtin (which also makes your string value immutable), it works in ES5 as well:
function SomeObject(a, b) {
this.a = a;
this.b = b;
}
SomeObject.prototype = Object.create(String.prototype);
SomeObject.prototype.constructor = SomeObject;
SomeObject.prototype.toString = function() {
return this.a + " " + this.b;
};
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
5
Is this considered good practice? It seems like a misuse of inheritance.
– usr
Dec 17 at 18:48
2
@usr Maybe it is, I don't know the OPs use case. However, if they want all ofString
s methods on their custom instances, that sounds quite a bit like subtyping.
– Bergi
Dec 17 at 18:52
add a comment |
You can let your objects inherit from String
so that all string methods become available:
class SomeObject extends String {
constructor(a, b) {
super(a + " " + b);
this.a = a;
this.b = b;
}
}
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
No need to use complicated Proxy
solutions :-)
All the String.prototype
methods (except for .toString
, .valueOf
and [Symbol.iterator]
) are "intentionally generic; [they do] not require that its this
value be a String
object. Therefore, [they] can be transferred to other kinds of objects for use as a method." You can call them on any value, they will coerce it to a string (using .toString()
or .valueOf
as usual).
You don't even need to use ES6 class extends
to inherit from the builtin (which also makes your string value immutable), it works in ES5 as well:
function SomeObject(a, b) {
this.a = a;
this.b = b;
}
SomeObject.prototype = Object.create(String.prototype);
SomeObject.prototype.constructor = SomeObject;
SomeObject.prototype.toString = function() {
return this.a + " " + this.b;
};
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
5
Is this considered good practice? It seems like a misuse of inheritance.
– usr
Dec 17 at 18:48
2
@usr Maybe it is, I don't know the OPs use case. However, if they want all ofString
s methods on their custom instances, that sounds quite a bit like subtyping.
– Bergi
Dec 17 at 18:52
add a comment |
You can let your objects inherit from String
so that all string methods become available:
class SomeObject extends String {
constructor(a, b) {
super(a + " " + b);
this.a = a;
this.b = b;
}
}
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
No need to use complicated Proxy
solutions :-)
All the String.prototype
methods (except for .toString
, .valueOf
and [Symbol.iterator]
) are "intentionally generic; [they do] not require that its this
value be a String
object. Therefore, [they] can be transferred to other kinds of objects for use as a method." You can call them on any value, they will coerce it to a string (using .toString()
or .valueOf
as usual).
You don't even need to use ES6 class extends
to inherit from the builtin (which also makes your string value immutable), it works in ES5 as well:
function SomeObject(a, b) {
this.a = a;
this.b = b;
}
SomeObject.prototype = Object.create(String.prototype);
SomeObject.prototype.constructor = SomeObject;
SomeObject.prototype.toString = function() {
return this.a + " " + this.b;
};
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
You can let your objects inherit from String
so that all string methods become available:
class SomeObject extends String {
constructor(a, b) {
super(a + " " + b);
this.a = a;
this.b = b;
}
}
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
No need to use complicated Proxy
solutions :-)
All the String.prototype
methods (except for .toString
, .valueOf
and [Symbol.iterator]
) are "intentionally generic; [they do] not require that its this
value be a String
object. Therefore, [they] can be transferred to other kinds of objects for use as a method." You can call them on any value, they will coerce it to a string (using .toString()
or .valueOf
as usual).
You don't even need to use ES6 class extends
to inherit from the builtin (which also makes your string value immutable), it works in ES5 as well:
function SomeObject(a, b) {
this.a = a;
this.b = b;
}
SomeObject.prototype = Object.create(String.prototype);
SomeObject.prototype.constructor = SomeObject;
SomeObject.prototype.toString = function() {
return this.a + " " + this.b;
};
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
class SomeObject extends String {
constructor(a, b) {
super(a + " " + b);
this.a = a;
this.b = b;
}
}
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
class SomeObject extends String {
constructor(a, b) {
super(a + " " + b);
this.a = a;
this.b = b;
}
}
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
function SomeObject(a, b) {
this.a = a;
this.b = b;
}
SomeObject.prototype = Object.create(String.prototype);
SomeObject.prototype.constructor = SomeObject;
SomeObject.prototype.toString = function() {
return this.a + " " + this.b;
};
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
function SomeObject(a, b) {
this.a = a;
this.b = b;
}
SomeObject.prototype = Object.create(String.prototype);
SomeObject.prototype.constructor = SomeObject;
SomeObject.prototype.toString = function() {
return this.a + " " + this.b;
};
var obj = new SomeObject('this', 'that');
console.log(obj.split(""));
edited Dec 17 at 12:41
answered Dec 17 at 9:17
Bergi
363k58540866
363k58540866
5
Is this considered good practice? It seems like a misuse of inheritance.
– usr
Dec 17 at 18:48
2
@usr Maybe it is, I don't know the OPs use case. However, if they want all ofString
s methods on their custom instances, that sounds quite a bit like subtyping.
– Bergi
Dec 17 at 18:52
add a comment |
5
Is this considered good practice? It seems like a misuse of inheritance.
– usr
Dec 17 at 18:48
2
@usr Maybe it is, I don't know the OPs use case. However, if they want all ofString
s methods on their custom instances, that sounds quite a bit like subtyping.
– Bergi
Dec 17 at 18:52
5
5
Is this considered good practice? It seems like a misuse of inheritance.
– usr
Dec 17 at 18:48
Is this considered good practice? It seems like a misuse of inheritance.
– usr
Dec 17 at 18:48
2
2
@usr Maybe it is, I don't know the OPs use case. However, if they want all of
String
s methods on their custom instances, that sounds quite a bit like subtyping.– Bergi
Dec 17 at 18:52
@usr Maybe it is, I don't know the OPs use case. However, if they want all of
String
s methods on their custom instances, that sounds quite a bit like subtyping.– Bergi
Dec 17 at 18:52
add a comment |
One option would be to return a Proxy
that checks whether the property exists on String.prototype
, and if it does, calls that property with the string that represents the object:
// Declare the proxy handler up front here
// to avoid unnecessary creation of duplicate handler objects
const handler = {
get(obj, prop) {
if (obj[prop] !== undefined) {
return obj[prop];
}
const stringMethod = String.prototype[prop];
if (stringMethod) {
return stringMethod.bind(obj.a + ' ' + obj.b);
}
},
};
const SomeClass = function(a, b) {
this.a = a;
this.b = b
return new Proxy(this, handler);
}
const instance = new SomeClass('this', 'that');
// String methods:
console.log(instance.trim());
console.log(instance.includes('this'));
console.log(instance.includes('somethingelse'));
console.log(instance.split(''));
// Can still assign and retrieve values directly on the object as normal:
instance.foo = 'foo';
console.log(instance.foo);
This options is really good, +1
– Just code
Dec 17 at 6:49
2
+1. Remark: this definition is only available in ecmascript 6 or later. Reference
– devildelta
Dec 17 at 6:51
3
I would recommend to declare the handler object outside of the constructor function, for the same reason that you should define methods on the prototype. Then you'd also use thetarget
argument instead of closing overthis
.
– Bergi
Dec 17 at 9:30
add a comment |
One option would be to return a Proxy
that checks whether the property exists on String.prototype
, and if it does, calls that property with the string that represents the object:
// Declare the proxy handler up front here
// to avoid unnecessary creation of duplicate handler objects
const handler = {
get(obj, prop) {
if (obj[prop] !== undefined) {
return obj[prop];
}
const stringMethod = String.prototype[prop];
if (stringMethod) {
return stringMethod.bind(obj.a + ' ' + obj.b);
}
},
};
const SomeClass = function(a, b) {
this.a = a;
this.b = b
return new Proxy(this, handler);
}
const instance = new SomeClass('this', 'that');
// String methods:
console.log(instance.trim());
console.log(instance.includes('this'));
console.log(instance.includes('somethingelse'));
console.log(instance.split(''));
// Can still assign and retrieve values directly on the object as normal:
instance.foo = 'foo';
console.log(instance.foo);
This options is really good, +1
– Just code
Dec 17 at 6:49
2
+1. Remark: this definition is only available in ecmascript 6 or later. Reference
– devildelta
Dec 17 at 6:51
3
I would recommend to declare the handler object outside of the constructor function, for the same reason that you should define methods on the prototype. Then you'd also use thetarget
argument instead of closing overthis
.
– Bergi
Dec 17 at 9:30
add a comment |
One option would be to return a Proxy
that checks whether the property exists on String.prototype
, and if it does, calls that property with the string that represents the object:
// Declare the proxy handler up front here
// to avoid unnecessary creation of duplicate handler objects
const handler = {
get(obj, prop) {
if (obj[prop] !== undefined) {
return obj[prop];
}
const stringMethod = String.prototype[prop];
if (stringMethod) {
return stringMethod.bind(obj.a + ' ' + obj.b);
}
},
};
const SomeClass = function(a, b) {
this.a = a;
this.b = b
return new Proxy(this, handler);
}
const instance = new SomeClass('this', 'that');
// String methods:
console.log(instance.trim());
console.log(instance.includes('this'));
console.log(instance.includes('somethingelse'));
console.log(instance.split(''));
// Can still assign and retrieve values directly on the object as normal:
instance.foo = 'foo';
console.log(instance.foo);
One option would be to return a Proxy
that checks whether the property exists on String.prototype
, and if it does, calls that property with the string that represents the object:
// Declare the proxy handler up front here
// to avoid unnecessary creation of duplicate handler objects
const handler = {
get(obj, prop) {
if (obj[prop] !== undefined) {
return obj[prop];
}
const stringMethod = String.prototype[prop];
if (stringMethod) {
return stringMethod.bind(obj.a + ' ' + obj.b);
}
},
};
const SomeClass = function(a, b) {
this.a = a;
this.b = b
return new Proxy(this, handler);
}
const instance = new SomeClass('this', 'that');
// String methods:
console.log(instance.trim());
console.log(instance.includes('this'));
console.log(instance.includes('somethingelse'));
console.log(instance.split(''));
// Can still assign and retrieve values directly on the object as normal:
instance.foo = 'foo';
console.log(instance.foo);
// Declare the proxy handler up front here
// to avoid unnecessary creation of duplicate handler objects
const handler = {
get(obj, prop) {
if (obj[prop] !== undefined) {
return obj[prop];
}
const stringMethod = String.prototype[prop];
if (stringMethod) {
return stringMethod.bind(obj.a + ' ' + obj.b);
}
},
};
const SomeClass = function(a, b) {
this.a = a;
this.b = b
return new Proxy(this, handler);
}
const instance = new SomeClass('this', 'that');
// String methods:
console.log(instance.trim());
console.log(instance.includes('this'));
console.log(instance.includes('somethingelse'));
console.log(instance.split(''));
// Can still assign and retrieve values directly on the object as normal:
instance.foo = 'foo';
console.log(instance.foo);
// Declare the proxy handler up front here
// to avoid unnecessary creation of duplicate handler objects
const handler = {
get(obj, prop) {
if (obj[prop] !== undefined) {
return obj[prop];
}
const stringMethod = String.prototype[prop];
if (stringMethod) {
return stringMethod.bind(obj.a + ' ' + obj.b);
}
},
};
const SomeClass = function(a, b) {
this.a = a;
this.b = b
return new Proxy(this, handler);
}
const instance = new SomeClass('this', 'that');
// String methods:
console.log(instance.trim());
console.log(instance.includes('this'));
console.log(instance.includes('somethingelse'));
console.log(instance.split(''));
// Can still assign and retrieve values directly on the object as normal:
instance.foo = 'foo';
console.log(instance.foo);
edited Dec 17 at 10:16
answered Dec 17 at 6:39
CertainPerformance
75.2k143659
75.2k143659
This options is really good, +1
– Just code
Dec 17 at 6:49
2
+1. Remark: this definition is only available in ecmascript 6 or later. Reference
– devildelta
Dec 17 at 6:51
3
I would recommend to declare the handler object outside of the constructor function, for the same reason that you should define methods on the prototype. Then you'd also use thetarget
argument instead of closing overthis
.
– Bergi
Dec 17 at 9:30
add a comment |
This options is really good, +1
– Just code
Dec 17 at 6:49
2
+1. Remark: this definition is only available in ecmascript 6 or later. Reference
– devildelta
Dec 17 at 6:51
3
I would recommend to declare the handler object outside of the constructor function, for the same reason that you should define methods on the prototype. Then you'd also use thetarget
argument instead of closing overthis
.
– Bergi
Dec 17 at 9:30
This options is really good, +1
– Just code
Dec 17 at 6:49
This options is really good, +1
– Just code
Dec 17 at 6:49
2
2
+1. Remark: this definition is only available in ecmascript 6 or later. Reference
– devildelta
Dec 17 at 6:51
+1. Remark: this definition is only available in ecmascript 6 or later. Reference
– devildelta
Dec 17 at 6:51
3
3
I would recommend to declare the handler object outside of the constructor function, for the same reason that you should define methods on the prototype. Then you'd also use the
target
argument instead of closing over this
.– Bergi
Dec 17 at 9:30
I would recommend to declare the handler object outside of the constructor function, for the same reason that you should define methods on the prototype. Then you'd also use the
target
argument instead of closing over this
.– Bergi
Dec 17 at 9:30
add a comment |
One option to extend the SomeObject
too, something like this.
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
SomeObject.prototype.split = function() {
return String.prototype.split.apply(this.toString(), arguments);
};
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
In a comment you've asked:
I was thinking about doing this programmatically by doing it for all functions - but is there a way to list all functions of an object?
Yes, you'd use getOwnPropertyNames
on String.prototype
and filter out the ones that aren't functions:
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
Object.getOwnPropertyNames(String.prototype).forEach(function(name) {
var fn = String.prototype[name];
if (name !== "toString" && typeof fn === "function") {
SomeObject.prototype[name] = function() {
return fn.apply(this.toString(), arguments);
};
}
});
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
Interesting thought. I was thinking about doing this programmatically by doing it for all functions - but is there a way to lost all functions of an object?
– simone
Dec 17 at 6:51
@simonelost all functions of an object
you mean? Do it only if you have custom requirements, doesn't makes sense if you do it for all the functions.
– Just code
Dec 17 at 6:54
"lost" should have been "list" - list all functions of an object
– simone
Dec 17 at 7:02
@simone to handle all the functions of an object, you can use certainperformance's solution.
– Just code
Dec 17 at 7:03
I was wondering about performance in using Proxy. Same as in setting the prototype in a deleted solution. But both look quite interesting...
– simone
Dec 17 at 7:04
|
show 2 more comments
One option to extend the SomeObject
too, something like this.
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
SomeObject.prototype.split = function() {
return String.prototype.split.apply(this.toString(), arguments);
};
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
In a comment you've asked:
I was thinking about doing this programmatically by doing it for all functions - but is there a way to list all functions of an object?
Yes, you'd use getOwnPropertyNames
on String.prototype
and filter out the ones that aren't functions:
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
Object.getOwnPropertyNames(String.prototype).forEach(function(name) {
var fn = String.prototype[name];
if (name !== "toString" && typeof fn === "function") {
SomeObject.prototype[name] = function() {
return fn.apply(this.toString(), arguments);
};
}
});
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
Interesting thought. I was thinking about doing this programmatically by doing it for all functions - but is there a way to lost all functions of an object?
– simone
Dec 17 at 6:51
@simonelost all functions of an object
you mean? Do it only if you have custom requirements, doesn't makes sense if you do it for all the functions.
– Just code
Dec 17 at 6:54
"lost" should have been "list" - list all functions of an object
– simone
Dec 17 at 7:02
@simone to handle all the functions of an object, you can use certainperformance's solution.
– Just code
Dec 17 at 7:03
I was wondering about performance in using Proxy. Same as in setting the prototype in a deleted solution. But both look quite interesting...
– simone
Dec 17 at 7:04
|
show 2 more comments
One option to extend the SomeObject
too, something like this.
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
SomeObject.prototype.split = function() {
return String.prototype.split.apply(this.toString(), arguments);
};
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
In a comment you've asked:
I was thinking about doing this programmatically by doing it for all functions - but is there a way to list all functions of an object?
Yes, you'd use getOwnPropertyNames
on String.prototype
and filter out the ones that aren't functions:
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
Object.getOwnPropertyNames(String.prototype).forEach(function(name) {
var fn = String.prototype[name];
if (name !== "toString" && typeof fn === "function") {
SomeObject.prototype[name] = function() {
return fn.apply(this.toString(), arguments);
};
}
});
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
One option to extend the SomeObject
too, something like this.
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
SomeObject.prototype.split = function() {
return String.prototype.split.apply(this.toString(), arguments);
};
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
In a comment you've asked:
I was thinking about doing this programmatically by doing it for all functions - but is there a way to list all functions of an object?
Yes, you'd use getOwnPropertyNames
on String.prototype
and filter out the ones that aren't functions:
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
Object.getOwnPropertyNames(String.prototype).forEach(function(name) {
var fn = String.prototype[name];
if (name !== "toString" && typeof fn === "function") {
SomeObject.prototype[name] = function() {
return fn.apply(this.toString(), arguments);
};
}
});
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
SomeObject.prototype.split = function() {
return String.prototype.split.apply(this.toString(), arguments);
};
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
SomeObject.prototype.split = function() {
return String.prototype.split.apply(this.toString(), arguments);
};
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
Object.getOwnPropertyNames(String.prototype).forEach(function(name) {
var fn = String.prototype[name];
if (name !== "toString" && typeof fn === "function") {
SomeObject.prototype[name] = function() {
return fn.apply(this.toString(), arguments);
};
}
});
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
var SomeObject = function(a, b){
this.a = a;
this.b = b
}
SomeObject.prototype.toString = function(){
return [ this.a, this.b ].join(' ')
};
Object.getOwnPropertyNames(String.prototype).forEach(function(name) {
var fn = String.prototype[name];
if (name !== "toString" && typeof fn === "function") {
SomeObject.prototype[name] = function() {
return fn.apply(this.toString(), arguments);
};
}
});
var objInstance = new SomeObject('this', 'that');
console.log(objInstance + '') // this that
//console.log(("" + objInstance).split('')) // [ 't', 'h', 'i', 's', ' ', 't', 'h', 'a', 't' ]
console.log(objInstance.split(''));
edited Dec 17 at 11:10
T.J. Crowder
677k12011971293
677k12011971293
answered Dec 17 at 6:41
Just code
8,71642966
8,71642966
Interesting thought. I was thinking about doing this programmatically by doing it for all functions - but is there a way to lost all functions of an object?
– simone
Dec 17 at 6:51
@simonelost all functions of an object
you mean? Do it only if you have custom requirements, doesn't makes sense if you do it for all the functions.
– Just code
Dec 17 at 6:54
"lost" should have been "list" - list all functions of an object
– simone
Dec 17 at 7:02
@simone to handle all the functions of an object, you can use certainperformance's solution.
– Just code
Dec 17 at 7:03
I was wondering about performance in using Proxy. Same as in setting the prototype in a deleted solution. But both look quite interesting...
– simone
Dec 17 at 7:04
|
show 2 more comments
Interesting thought. I was thinking about doing this programmatically by doing it for all functions - but is there a way to lost all functions of an object?
– simone
Dec 17 at 6:51
@simonelost all functions of an object
you mean? Do it only if you have custom requirements, doesn't makes sense if you do it for all the functions.
– Just code
Dec 17 at 6:54
"lost" should have been "list" - list all functions of an object
– simone
Dec 17 at 7:02
@simone to handle all the functions of an object, you can use certainperformance's solution.
– Just code
Dec 17 at 7:03
I was wondering about performance in using Proxy. Same as in setting the prototype in a deleted solution. But both look quite interesting...
– simone
Dec 17 at 7:04
Interesting thought. I was thinking about doing this programmatically by doing it for all functions - but is there a way to lost all functions of an object?
– simone
Dec 17 at 6:51
Interesting thought. I was thinking about doing this programmatically by doing it for all functions - but is there a way to lost all functions of an object?
– simone
Dec 17 at 6:51
@simone
lost all functions of an object
you mean? Do it only if you have custom requirements, doesn't makes sense if you do it for all the functions.– Just code
Dec 17 at 6:54
@simone
lost all functions of an object
you mean? Do it only if you have custom requirements, doesn't makes sense if you do it for all the functions.– Just code
Dec 17 at 6:54
"lost" should have been "list" - list all functions of an object
– simone
Dec 17 at 7:02
"lost" should have been "list" - list all functions of an object
– simone
Dec 17 at 7:02
@simone to handle all the functions of an object, you can use certainperformance's solution.
– Just code
Dec 17 at 7:03
@simone to handle all the functions of an object, you can use certainperformance's solution.
– Just code
Dec 17 at 7:03
I was wondering about performance in using Proxy. Same as in setting the prototype in a deleted solution. But both look quite interesting...
– simone
Dec 17 at 7:04
I was wondering about performance in using Proxy. Same as in setting the prototype in a deleted solution. But both look quite interesting...
– simone
Dec 17 at 7:04
|
show 2 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53809965%2fis-it-possible-to-automatically-stringify-in-javascript%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
So you want to be able to concatenate all values of an object and search through it. You're doing it for searching purpose right ?
– Walfrat
Dec 17 at 12:36
1
Just curious, what are you trying to do with this?
– Addison
Dec 17 at 16:40