I'm trying to call the age, name and height together, from only 1 variable called this.anh from the function called person.
The way i wrote the list is wrong but what is the right notation? if there is multiple ways, please write them down. :)
<script type="text/javascript">
function person(age, name, height){
this.age = age;
this.name = name;
this.height = height;
this.anh = age, name, height;
}
var koolz = new person(20,"koolz",200);
document.write(koolz.anh)
</script>
You need to add literals where you want them and concatenate the dynamic values.
function person(age, name, height){
this.age = age;
this.name = name;
this.height = height;
// If you want a literal comma and space to separate the values
// then you need to concatenate them to the variables.
this.anh = age + ", " + name + ", " + height;
// Or, if the data were in an array, like this:
var arry = [this.age, this.name, this.height ];
// You could concatenate them like this:
var result = arry.join(", ");
console.log(result);
}
var koolz = new person(20,"koolz",200);
document.write(koolz.anh)
You need to concatenate the variables to get your expected output.
this.anh = age + ', ' + name + ', ' + ', ' + height;
function person(age, name, height) {
this.age = age;
this.name = name;
this.height = height;
this.anh = function() {
return this.age + ", " + this.name + ", " + this.height;
};
this.anh2 = age + ", " + name + ", " + height;
}
var koolz = new person(20, "koolz", 200);
console.log(koolz.anh())
console.log(koolz.anh2)
koolz.age = 25;
koolz.height = 210;
console.log("This has the updated values.")
console.log(koolz.anh())
console.log("Other way doesn't ever change")
console.log(koolz.anh2)
Since age, name and height are public properties you should use a function for "anh" so that it always returns an up to date value. Otherwise "anh" could get out of sync with the other variables very easily.
ES5
this.anh = age + ', ' + name + ', ' + height;
ES6 (template literal)
this.anh = `${age}, ${name}, ${height}`;
And instead of creating a new variable, you can override the toString method:
function person(age, name, height) {
this.age = age;
this.name = name;
this.height = height;
}
person.prototype.toString = function () {
return this.age + ', ' + this.name + ', ' + this.height;
}
var koolz = new person(20, 'koolz', 200);
koolz.toString() // "20, koolz, 200"
Related
first and foremost i'm new to javascript and coding. second, i'm coding a book store project with javascript with an alert message that shows each customer's total factor. but the alert message shows the code of my function "printFactor" insted of the string that is made by this function. this is my code:
function Book(name, writer, date, price)
{
this.name = name;
this.writer = writer;
this.date = date;
this.price = price;
}
function Customer(name, gender, turn)
{
this.name = name;
this.gender = gender;
this.turn = turn;
this.numberOfBooks = 0;
this.totalSum = 0;
this.bookList = [new Book("-", "-", "-", 0)];
//Functions.
this.addBook = function (newBook) {
this.numberOfBooks++;
this.bookList.push(newBook);
};
this.printFactor = function () {
var message = "";
if (this.numberOfBooks === 0) {
message = "No Books Has Been Added to Book List!";
return (message);
}
else {
message = this.name + " " + this.gender + " Number of Books: " + this.numberOfBooks + " Customer's Turn: " + this.turn + "\nBooks:\n";
var i;
var newMessage;
for (i = bookList.length - 1; i > 0; i--) {
newMessage = bookList[i].name + " " + bookList[i].writer + " " + bookList[i].date + " " + bookList[i].price.toString() +"\n" ;
message += newMessage;
this.totalSum += bookList[i].price;
this.bookList.pop();
}
newMessage = "Total Sum: " + this.totalSum;
message += newMessage;
return (message);
}
};
}
var book = new Book("Faramarz Bio", "Faramarz Falsafi Nejad", "1377/04/29", 13000);
var faramarz = new Customer("faramarz", "Male", 3);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
var m = faramarz.printFactor;
window.alert(m);
You need to invoke the function:
var m = faramarz.printFactor();
As is your variable m contains a reference to the function, but you need to call it to get the result.
var m = faramarz.printFactor();
window.alert(m);
You simply don't call your function, this should work.
var m = faramarz.printFactor()
Beside you reference an unexisting variable 'booklist', that should be "this.booklist"
for (i = this.bookList.length - 1; i > 0; i--) {
newMessage = this.bookList[i].name + " " + this.bookList[i].writer + " " + this.bookList[i].date + " " + this.bookList[i].price.toString() +"\n" ;
You need to actually call the function by adding () to the end, like this:
var m = faramarz.printFactor()
var peopleFactory = function(name, age, height) {
var temp = {};
this.name = name;
this.age = age;
this.height = height;
temp.printPerson = function() {
console.log(this.name + '' + this.age + '' + this.height);
document.write(this.name + '' + this.age + '' + this.height);
};
return temp;
};
var person1 = peopleFactory('tanmay', 27, 5.11);
var person2 = peopleFactory('chinmay', 37, 5.12);
person1.printPerson();
person2.printPerson();
Not sure but here you go. Just make it a class.
class peopleFactory {
constructor(name, age, height) {
this.name = name;
this.age = age;
this.height = height;
}
printPerson() {
return this.name + ' ' + this.age + ' ' + this.height;
};
};
var person1 = new peopleFactory('tanmay', 27, 5.11);
console.log(person1.printPerson())
You should not be using this in your factory as it's a reference to the global object (unless you want to call your factory with the new keyword. But then, it wouldn't be a factory anymore).
Instead, you could be using another local object where you would store your object's private data. By doing that, your printPerson() function becomes a closure and can access data inside that local object and will be able to print it once it's invoked.
var peopleFactory = function(name, age, height) {
var temp = {}, instance = {};
temp.name = name;
temp.age = age;
temp.height = height;
instance.printPerson = function() {
console.log(temp.name + ' ' + temp.age + ' ' + temp.height);
document.write('<br/>' + temp.name + ' ' + temp.age + ' ' + temp.height);
};
return instance;
};
var person1 = peopleFactory('tanmay', 27, 5.11);
var person2 = peopleFactory('chinmay', 37, 5.12);
person1.printPerson();
person2.printPerson();
I know I can use the Invocable class to invoke methods on a class:
import javax.script.{ScriptEngine, ScriptEngineManager, Invocable}
val engine = new ScriptEngineManager().getEngineByExtension("js")
val invoker = engine.asInstanceOf[Invocable]
val person = engine.eval(s"""
new function () {
this.name = "Rick";
this.age = 28;
this.speak = function () {
return this.name + "-" + this.age;
}
};
""")
invoker.invokeMethod(person, "speak") //returns "Rick-28"
But, how do I get the name attribute of the person? I tried invoker.invokeMethod(person, "name") and I got a NoSuchMethodError.
You can cast person to a JSObject and then call person.getMember("name"). Full Java example:
ScriptEngine engine = new ScriptEngineManager()
.getEngineByExtension("js");
JSObject rick = (JSObject) engine.eval("new function () {\n" +
" this.name = \"Rick\";\n" +
" this.age = 28;\n" +
" this.speak = function () {\n" +
" return this.name + \"-\" + this.age;\n" +
" }\n" +
" };");
System.out.println(rick.getMember("name"));
Or, if the object is stored in the engine global scope like in the following javascript source:
rick = function() {
this.name= "Rick";
};
you can then call
engine.eval("rick.name");
I have this object:
function Boy(n,s,a)
{
this.name = n;
this.surname = s;
this.age = a;
this.getInfo = function(){
return this.name + ' ' + this.surname + ' (' + this.age + ')';
}
}
I want to do something like this:
{{ boy.getInfo() }}
and not like this:
{{ boy.name }} {{ boy.surname }} ({{boy.age}})
is it possible?
there are some tricks for doing something similar?
Absolutely! You can create an object and shove it into $scope just like anything else.
var NameController = function ($scope) {
$scope.boy = new Boy("Foo", "Bar", 32);
};
NameController.$inject = ['$scope'];
app.controller("NameController", NameController);
And then bind it in the UI just like so:
<h3>{{boy.getInfo()}}</h3>
Here is an example of binding to all three properties and seeing the result of the function: http://jsfiddle.net/jwcarroll/Pb3Cu/
You can bind $scope functions normally
function MyController($scope){
$scope.myfunc = function(){
return "test";
}
}
and then, in the view
{{ myfunc() }}
You can do something like:
function Boy(n,s,a)
{
this.name = n;
this.surname = s;
this.age = a;
this.getInfo = function(){
return this.name + ' ' + this.surname + ' (' + this.age + ')';
}
}
var boy = new Boy(n, s, a);
$scope.boy = function(){
return boy.getInfo();
}
And in you template just bind {{boy()}}.
Hai,
I am trying to understand few concepts in JavaScript. Consider the following code:
function Person(name, age)
{
this.name = name || "no name";
this.age = age || "age not specified";
this.printStr = function()
{
console.log("< " + this.name + ", " + this.age + " >");
};
}
p = new Person("pranav", 26);
p.printStr = function()
{
console.log("this works. also ...." + this.name);
};
p.printStr();
I want to call the implementation of 'printStr' in Person class from within the implementation of 'printStr' function in 'p'.
such that the output should be:
< pranav, 26 >
this works. also ....pranav
Any ideas? :)
The way your code is set up now, you can't do it. When you call Person as a constructor, the object that ends up being p gets set to this. So when you define printStr in the constructor, p gets an attribute called printStr. You then over-write it when you assign the second function.
Two options: A non-answer is to do what pablochan did - have the internal one be called oldPrintStr. Another option is to use the prototype inheritance:
function Person(name, age)
{
this.name = name || "no name";
this.age = age || "age not specified";
}
Person.prototype.printStr = function() {
console.log("< " + this.name + ", " + this.age + " >");
};
Then you can do this:
p = new Person("pranav", 26);
p.printStr = function()
{
Person.prototype.printStr.apply(this);
console.log("this works. also ...." + this.name);
};
p.printStr();
As far as I know there is no real subclassing in JS so to do this you should probably save the old function and then replace it.
p = new Person("pranav", 26);
p.oldPrintStr = p.printStr;
p.printStr = function()
{
p.oldPrintStr();
console.log("this works. also ...." + this.name);
};
p.printStr();
unless you save Person's printStr you can always create a temp Person object solely to extract printStr and call it:
p.printStr = function()
{
print("this works. also ...." + this.name);
(new Person()).printStr.apply(this);
};
but I guess you'll be better off if you make Person's original printStr accessible via prototype:
Person.prototype.printStr = function()
{
print("< " + this.name + ", " + this.age + " >");
};
then you have no need for temp object or saving old function and can do:
Person.prototype.printStr.apply(this);