Suppose I have two constructor function:
var Person = function(xx,xx,xxx,xxxxxxx) {
//Person initialization
}
var Man = function(xx,xx,xxx,xxx) {
//Man initialization
}
And I want Man extends from Person.
The following is what I thought:
Given a created Man object:
var m=new Man("xx",....);
1) when a property of m is accessed,it will search it in Man.prototype.
2) If not find, It should find it in Man.prototype.__prop__.
So what I have do is make the Man.prototype.__prop__ linked to Person.prototype.
I know this is the common way:
function inherit(superClass) {
function F() {}
F.prototype = superClass.prototype;
return new F;
}
Man.prototype=inherit(Person);
But when I try this:
Man.prototype.prototype=Person.prototype.
Why it does not work?
It sounds like you actually want to link instances of Man to an instance of Person that retains any properties added in its constructor, in which case you might really want something like this:
function Person(a, b) {
this.a = a;
this.b = b;
}
function Man() {}
Man.prototype = new Person("val1", "val2");
var m = new Man();
console.log(m.a);
...which prints val1.
Additional Ramblings
The purpose of inherit is to create an object from a function whose prototype is that of the given super class (without explicitly using new), which is exactly what it does. Therefore, the following prints string:
function Person() {}
Person.prototype.test = "string";
function Man() {}
function inherit(superClass) {
function F() {}
F.prototype = superClass.prototype;
return new F;
}
var t = inherit(Person);
console.log(t.test);
But you generally want to assign the returned object to another function's prototype:
Man.prototype = inherit(Person);
var m = new Man();
console.log(m.test);
...so that m.test also prints string, which means that objects created using Man are linked to Person's prototype).
Note that Man.prototype.prototype is undefined and -- this is the important part -- also meaningless. Functions have prototypes. Other objects (such as Man.prototype) do not. The prototype property is not magical in any other context. Assigning a value to a random object's prototype property doesn't do anything special. It's just another property.
Note also that the thing we returned from inherit is linked to Person by way of its prototype and has no access to any properties added to instances of Person.
How I do it (in regards to your example):
var Person = function () {
}
// Define "Person" methods
var Man = function () {
}
Man.prototype = new Person();
// Define "Man" methods
UPDATE
Regarding constructors with parameters: just found this SO question that can really help you figure it out (second answer, first part): JavaScript inheritance: when constructor has arguments.
There are quite a few generic methods to do that. I will provide three of them:
1.) Using Function object as a constructor and as a prototype object for inherited new objects. The implementation should look like as the following:
var person = {
toString : function() {
return this.firstName + ' ' + this.lastName;
}
}
function extend(constructor, obj) {
var newObj = Object.create(constructor);
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
newObj[prop] = obj[prop];
}
}
return newObj;
}
var man = extend(person,
{
sex: "male",
age: "22"
});
var name = extend(man,
{
firstName: "Simo",
lastName: "Endre"
});
name.man;
name.toString();
2.) In this case we'll use the Function object as the constructor for simulating the classical inheritance in a language like C# or Java. The prototype property of an object will be used in the role of a constructor and the the newly created object will inherit all the properties from the object prototype root. In this case the object's prototype has only one kind of augmentation role, the effective implementation is done in the function method.
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.toString = function() {
return this.firstName + ' ' + this.lastName;
}
function inherit(func) {
// passing function arguments into an array except the first one which is the function object itself
var args = Array.prototype.slice.call(arguments, 1);
// invoke the constructor passing the new Object and the rest of the arguments
var obj = Object.create(func.prototype);
func.apply(obj, args);
//return the new object
return obj;
}
var man = inherit(Person, "Simo", "Endre");
man.toString();
3.) The well known inheritance model:
function extend(o) {
function F() {}
// We'll set the newly created function prototype property to the object.
//This act as a constructor.
F.prototype = o;
// Using the `new` operator we'll get a new object whose prototype is o.
return new F();
};
Related
I know that, we can create the new instance of functions by the following approach. But my question is there any other way to achieve the same?
var Person = function (firstName) {
this.firstName = firstName;
console.log('Person instantiated');
};
var person1 = new Person('Alice');
var person2 = new Person('Bob');
// Show the firstName properties of the objects
console.log('person1 is ' + person1.firstName); // logs "person1 is Alice"
console.log('person2 is ' + person2.firstName); // logs "person2 is Bob"
Since, some time in case of new declaration fails, i am not getting the error too..
Especially, in javascript oops concept requires the different approach.
Some times, I am confusing without even calling the new key words it all works fine.. what is the different between using the new keyword and without using that?
example :
var setColor = function (color) {
return color;
}
var x = setColor('red');
var y = setColor('blue');
console.log(y);
console.log(x);
The new [Function] keyword does many things, but the main things it does are:
Creates a new object
Uses [Function]'s prototype as the parent prototype for the new object
Executes the contents of [Function], using this as a reference to the new object
If you call such a function without new, the this reference will be determined the way it would usually be determined when calling a function, and quite often this would be the global object.
One thing you can do to help catch these mistakes more easily is to use strict mode:
"use strict";
var Person = function (firstName) {
this.firstName = firstName;
console.log('Person instantiated');
};
var person1 = Person('Alice');
If the above code were executed, this would be null instead of the global object, and you would get an error right away instead of having the properties assigned to the global object (and having hard-to-catch bugs).
A way to avoid these kinds of mistakes with new altogether is to simply have the function return a new object instead of being a constructor:
var person = function (firstName) {
console.log('person instantiated');
return {
firstName: firstName
};
};
var person1 = person('Alice');
var person2 = person('Bob');
If you do this, it doesn't matter whether you use new or not, because the function doesn't use this.
Edit There was a question below about prototypes. If you are unfamiliar with prototypes, this is a feature that allows you to specify properties and methods that will be shared between all instances of an object:
"use strict";
var Person = function (firstName) {
this.firstName = firstName;
console.log('Person instantiated');
};
Person.prototype.getMyName = function () {
return this.firstName;
};
var person1 = new Person('Alice');
console.log(person1.getMyName());
If you do this, then all instances created with new Person() will share the getMyName method.
The new-less option I detailed later on does not provide this automatic prototype extension, but there are alternatives:
Option 1 - don't use a prototype:
var person = function (firstName) {
console.log('person instantiated');
return {
firstName: firstName,
getMyName: function () {
return this.firstName;
}
};
};
Option 2 - Use Object.create() to extend the prototype:
var person = function (firstName) {
console.log('person instantiated');
var person = Object.create(person.prototype);
person.firstName = firstName;
return person;
};
Option 3 - Use Object.assign() method to copy the contents of the prototype to a new object:
var person = function (firstName) {
console.log('person instantiated');
return Object.assign({
firstName: firstName
}, person.prototype);
};
Using the new keyword when you call a function sets the context (this) inside the function to be a newly instantiated object, rather than window or some other context, which is why you can assign to this.firstName inside the function, and then refer to it as person1.firstName.
Without using the new keyword, the value of this WONT be a blank object, so you will be assigning to window instead. In this case, you want to use new since you are using the function as a constructor. If you aren't planning to use the function as a constructor, you don't want to call it with new.
Another possible structure using closures and not objects at all
This structure also can be nested creating private static variables
It has no use of the word this
var thing = function(private_var){
function get(){
console.log(private_var)
}
function set(z){
private_var = z
}
return {
get:get,
set:set
}
}
var x = thing(0)
var y = thing(1)
Please note :
This makes certain types of programmers freak out and panic
&& importantly x.say !== y.say
I think you need a bit better understanding of how objects and prototyping work in Javascript.
Consider you have a use case where you want an object that represents a user, and stores their first_name.
Without using any functions, you can simply create an object with your desired properties:
var person = {
first_name: 'joel'
};
This is a standard javascript object - nothing special at all, and no usage of the new keyword to construct it. An alternate syntax to accomplish the same thing would be:
var person = new Object();
person.first_name = 'joel';
Again - this is just a standard object - nothing special at all.
The main reason for creating new instances of a function, is to use javascript's prototyping system. This is similar to a class in other languages. Let's say you wanted all instances of a person to have a method called getName(). You could either make sure you create that method on every person you have...
var person = {
first_name: 'joel',
getName: function() {
return this.first_name;
}
};
or...
var person = new Object();
person.first_name = 'joel';
person.getName = function() {
return this.first_name;
};
However a better approach for this kind of thing, where you're always going to want this method defined for every user, is to create a new instance of a person object, and define the getName method on the prototype property of the Person function:
function Person() {}
Person.prototype.getName = function() {
return this.first_name;
}
var user = new Person();
user.first_name = 'joel';
console.log(user.getName());
... Or as per your example, you can use a parameter to the Person constructor function to set the first name property:
function Person(first_name) {
this.first_name = first_name;
}
Person.prototype.getName = function() {
return this.first_name;
};
var user = new Person('joel');
console.log(user.getName());
Note that using this method you would always use the new keyword when creating a Person instance. The reason for this becomes clear when you consider the followng:
function Person() {this.first_name = 'joel'; return 'test';}
console.log(window.first_name); // Undefined, as expected
console.log(Person()); // Shows "test";
console.log(window.first_name); // shows "joel".
console.log(new Person()); // Shows "{first_name: 'joel'}"
Note that on line 4 above, you can see that by omitting the new keyword on a function call that expects you to be using it, you've accidentally modified a property on the window object, instead of setting it on a new regular object.
Effectively - you can consider usage of the new keyword to cause the return value of the Person function to be disrecarded, and instead you'll be given back a new instance of the Person Object.
Also note that you can reduce the risk of accidental modifying of the window object by omitting the new keyword from inside your function, by checking if this is equal to window and returning a new instance of your function instead:
function Person() {
if (this === window) return new Person();
this.first_name = 'joel';
}
With the above, you can instantiate your person object using either of the following methods and both will have the same effect:
var user1 = new Person();
var user2 = Person();
For some more information on how javascript functions and prototype objects work, I suggest reading http://www.w3schools.com/js/js_object_prototypes.asp
I've been reading Is JavaScript's "new" keyword considered harmful? and this Adobe Article on using prototypal inheritance rather than 'new'. The Adobe article has a 'new' example:
function Foo() {
this.name = "foo";
}
Foo.prototype.sayHello = function() {
alert("hello from " + this.name);
};
...that it replaces with:
var foo = {
name: "foo",
sayHello: function() {
alert("hello from " + this.name);
}
};
Here the 'sayHello' method isn't attached to the object's prototype. Doesn't this mean 'sayHello' gets unnecessarily duplicated in memory (I know V8 avoids this, but in older JS engines, for example) as it is copied to all objects that inherit from foo?
Shouldn't it be:
var foo = {
name: "foo",
prototype: {
sayHello: function() {
alert("hello from " + this.name);
}
}
};
Or similar?
The method is not attached to the prototype because this very object becomes the prototype that is attached to newly created objects with Object.create. And you don't need a prototype of the prototype.
Remember that Object.create doesn't deep clone objects. Rather, it is equivalent to something like
Object.create = function(proto) {
function F() {}
F.prototype = proto;
return new F();
}
(actual implementation is more complicated but this short version illustrates the idea)
All newly created objects "inherit" the method from the foo which acts as the prototype and there is no duplication here.
No, it won't get duplicated if you create another object using that as a protoype. The almost equivalent code using Object.create is actually slightly different, you are not using the prototype, you are just creating an object. To use prototypal inheritance, do the following. Note that using new still sets up the prototype chain so the title of the article you linked to is not very accurate and you are still sharing the properties on a single object.
var foo = {
name: "foo",
sayHello: function() {
alert("hello from " + this.name);
}
};
var extended = Object.create(foo);
var extended2 = Object.create(foo);
extended.name = "first";
extended2.name = "second";
extended.sayHello(); // hello from first
extended2.sayHello(); // hello from second
// Methods are shared, outputs true
console.log(extended.sayHello === extended2.sayHello)
// Now if you delete the property again, it will go up the chain
delete extended.name;
extended.sayHello(); // hello from foo
You could also just do
var extended = Object.create(Foo.prototype);
It would get duplicated if you create a constructor to get new instances instead of Object.create or new Foo
function createFoo() {
return {
name: "foo",
sayHello: function() {
alert("hello from " + this.name);
}
}
}
var a = createFoo();
var b = createFoo();
// The function objects are not shared
alert('Are functions the same? ' + a.sayHello === b.createFoo);
They would also not be shared if you use the closure approach to creating objects. Crockford suggests that to create truly private members. I don't use it because it doesn't use the prototype chain and inheritance is tricky to implement without just copying properties.
Function Foo() {
var name = 'foo';
this.sayHello = function () {
alert(name);
};
this.setName = function (newName) {
name = newName;
};
}
var a = new Foo();
var b = new Foo();
console.log(a.sayHello === b.sayHello); // outputs false
Going to answer my own question here, for my own notes and also to help explain to others:
Q. Using Object.create(), should exemplars have methods attached to their prototype property?
A. No, because Object.create(parentObject) itself sets up the parentObject as the prototype of a dynamically-created constructor.
Also: prototype is always a property on constructor Functions - not on regular Objects. Eg:
var someArray = [];
someArray.__proto__ === Array.prototype
Object.create() dynamically creates constructors, setting the prototype on them to the object in its first argument.
If we have a parent object like:
var Animal = function(name) {
this.name = name;
return this;
}
and we use prototype like:
Animal.prototype.Dog = function(){
console.log(this.name);
}
this just works great.
But what I am trying to achieve is to inherit the parent property in child object like
Animal.prototype.Child = {
Dog : function(){
console.log(this.name);
}
}
How can we do this. I am trying to find it for two days. I've also tried:
Animal.prototype.Child = {
that:this,
Dog : function(){
console.log(this.that.name);
}
}
But here that contains the window object not the Animal. Also
Animal.prototype.Child = {
Animal: new Animal('Puppy'),
Dog : function(){
console.log(this.Animal.name);
}
}
is NOT an option here.
Your inheritance chain doesn't look right. You'd create two different constructors. Each constructor creates an object. The inheritance part is setting up the prototype chain and calling "super" within the children class. In other words, you'd do this:
// Constructor for animals
function Animal(name) {
this.name = name;
// no need to return this
// as a constructor returns the instance
// when using the `new` keyword
}
// Public methods of all animals
Animal.prototype.say = function(){
// implement
};
// Constructor for dogs
function Dog(name) {
// Call "super", inherit parent properties
Animal.apply(this, arguments);
}
// Public methods of dogs
Dog.prototype.fetch = function(){
// implement
};
// Setup prototype inheritance chain
// and save a reference to our constructor
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Even though your inheritance didn't look right, this is a common misconception:
Animal.prototype.Child = {
that: this, //<---
...
}
this is the context of a function, and the value depends on how that function gets called. this in the code above is window; notice that there's no function.
In the code below, this is obj:
var obj = {
prop: 'foo',
method: function() {
return this.prop;
}
};
obj.method();
//^ logs "foo" because we are using dot notation (`obj` is the receiver)
If we call the function without dot notation it won't work. Again, this depends only on how the function gets called. This won't work:
var fn = obj.method;
fn(); // won't work
fn.call(obj); //=> will work, we pass the context explicitly
my question here is about functions and objects in javascript. I have three questions that stems from one to other. In the below example, I try to access the value of 'a' in test, but I get undefined. but I create a new object of test, then I am able to access the 'a' value and change it.
//create a function called test
var test=function() {
this.a=2
this.b=3 };
test.a//undefined
//create a object called test1 using 'new'
test1 = new test();
test1.a//2
//change the value of a in test1
test1.a=4
test1 //Object { a=4, b=3}
while trying to find why this happens, I came across this javascript functions are objects? and another question popped out of this.
The accepted solution for that SO question is below
var addn = function func(a) {
return func.n + a;
};
addn['n'] = 3;
addn(3);
I changed the 'func.n' to 'this' and it no longer works
var addn=function func(a) {
return this.n+a;
};
addn['n']=3;
addn(3); //NaN
making anonymous function with 'this' also did not help
//anonymous function
var addn=function(a) {
return this.n+a;
};
addn['n']=3;
addn(3); //NaN
why using 'this' did not work?
one final question, what is the difference in using keyword 'new' and 'createObject'. Douglas Crokford suggests using 'CreateObject' in his book, but I fail to understand why. Thanks all for your comments
1. Functions are constructors for new objects
When you call new FuncName, the function acts as a constructor, and the value of this inside points to the object being constructed (not the function itself). When you remove new, this becomes undefined, falling back to the global object (unless you're in strict mode).
2. Functions are also objects
Every function is an instance of Function, so the functions themselves are objects and can have have their own properties. Those properties cannot be accessed with this.propName inside the function body, only with funcName.propName. That's because this inside a function is never the function object itself (unless you forced it to be, with bind, call, or apply).
I hope both topics above help you understand how functions work. As for your final question: Crockford's createObject is a different way to implement inheritance, doing basically what Object.create does in ES5-compliant browsers. It allows an object to inherit straight from another object, without requiring you to manually create a new constructor, set its prototype property (which is an example of a property on a function object), and create an instance with new. Crockford prefers that, and said he stopped using new in favor of this approach.
In response to the questions you asked in chat, here is an attempt to explain what functions are and what they do, with examples.
Functions can be just... functions
You call them, they do something:
function alertThis(what) {
alert(what)
}
alertThis("alerting something");
You can also pass them values, and have them return values
function timesTwo(num) {
return num * 2;
}
timesTwo(2); // 4
They can be passed and return anything, including objects...
function createPerson(firstName, lastName) {
return {
firstName : firstName,
lastName : lastName
}
}
var john = createPerson('John', 'Doe');
john.lastName; // "Doe"
...and other functions:
function timesN(n) {
return function(num) {
return n * num;
}
}
var timesThree = timesN(3);
timesThree(5); // 15
Functions are objects
Functions can be passed around and returned like any ordinary object. That's because they are objects. Like any object, they can have properties:
function countCalls() {
countCalls.timesCalled++;
}
countCalls.timesCalled = 0;
countCalls();
countCalls();
countCalls.timesCalled; // 2
One very important default property of functions is prototype. It's a special property, and we'll see why.
Functions can act as constructors for new objects
Functions can behave like class constructors do in regular OO languages. When called with new, they create a new object of a certain "class". This new object is called this inside the function, and is automatically returned:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
var john = new Person('John', 'Doe');
john.firstName; // "John"
john instanceof Person; // true
... unless you deliberately return something else:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
var fakePerson = {
firstName : firstName,
lastName : lastName
};
return fakePerson;
}
var notPerson = new Person('John', 'Doe');
notPerson.firstName; // "John"
notPerson instanceof Person; // false
// Note: the object called 'this' inside the function is created, but
// after the function is called there is no outside reference to it.
Objects created by constructors know who created them, and can see their prototype property
Back to a real person:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Add something to the Person prototype
Person.prototype.sayHi = function() {
return "hi, I'm " + this.firstName;
}
var john = new Person('John', 'Doe');
john.sayHi(); // "Hi, I'm John"
john.constructor; // Person
The object john can sayHi() because it has access to everything inside its constructor's prototype property. But it cannot see other properties of Person directly (only through their own constructor property):
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
Person.timesCalled++;
// There is no 'this.timesCalled', only Person.timesCalled
}
Person.timesCalled = 0;
var john = new Person('John', 'Doe');
john.timesCalled; // undefined - john cannot be called, Person can
john.constructor.timesCalled; // 1
1.
addn['n'] = 3; //Means you add static property n to the function(object) addn.
so addn.n also work.
2
this.n means property n of the instance.
this.n === undefined so it returns NaN.
3 var addn=function func(a) means you give a second name to func.
var addn=function(a) is better format in most case.
4 createObject is not a native javaScript code. 'New' is.
When we make an object like this
function myObject(){
Properties and methods here----
};
We write “function” keyword before name of object is it necessary? All objects are functions in real? Can we not write direct object name like this?
myObject(){
Properties and methods here----
};
No, not all objects are functions. (All functions are objects, though.)
Here, obj isn't a function:
var obj = {
foo: "bar"
};
Nor dt here:
var dt = new Date();
The function keyword is necessary in order to say "what follows is a function declaration or function expression." It's just part of the basic syntax of JavaScript.
in the first case, the function can be used as the constructor for an object. So you can have:
function Person(name) {
this.name = name
}
Person.prototype = {
// methods can go in here
}
person1 = new Person("bob");
alert(person1.name) // alerts "bob"
It is also true that you can use a function as an object. For example:
function myObject() {
return myObject.test;
}
myObject.test = "bob";
alert(myObject()) // would alert "bob"
but all objects are not functions.
var someObject = {
name: "bob",
moody: "sad"
}
alert(someObject.name); // alerts "bob"
try {
someObject();
} catch (er) {
alert(er); // alerts "TypeError: object is not a function"
}
I'd suggest you take a look at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function
One reason is obviously disambiguity;
function foo()
{
alert("cake")
}
foo()
{
alert("burb");
}
foo();
alerts cake, burb, cake as the 2nd foo() {...} is just a regular function call followed by a regular compound statement enclosed in {}.
function declares a function. Because of the way JavaScript works, a function can be used as a class, to make objects.
But if you really just want an object, use squiggly braces, like this:
var myObject = {
x : 30, // a property
getX : function() { // a method
return this.x;
}
}
But your understanding of JavaScript needs a lot of work: read a few books about it.
In Javascript we can create objects in various ways:
1) Literals
let employee = {"name": "tyrion","age":34}
2) Constructor functions(functions having this)
function employee(name, age) {
this.name = name;
this.age = age;
}
let specificEmployee = new employee("tyrion",34);
Constructor function always need to have a new operator to create a object
3) Using Object constructor
let employee = Object.create(null);
employee.name = "tyrion";
employee.age = 34
In javascript every thing other than primitive type is an instance inherited from Object constructor.
No it's not required. You can also have:
var myObject = {
Prop1: "Value1",
Prop2: "Value2",
Method1: function() {
alert("hello");
}
};
Live test case: http://jsfiddle.net/rKunx/
You can write:
myObject = {
Properties and methods here----
}
If you want to avoid the function keyword as much as possible in Java you could use classes:
class Person {
name;
setName(name) {
this.name = name;
this.doStuff();
}
doStuff() {
//...
}
}
The obvious disadvantage to using classes though is that any property or function has to be accessed with this. An advantage of this keyword is that it is clear to know that you are referring to a class property or function and not a local one within the function.
Some people use a var or let in the top:
setName(name) {
let t = this;
t.name = name;
t.doStuff();
}
Still, many prefer to use a function to define some kind of class instead since that does not need this in order to reach the properties which are just variables in the scope of the function. Put inside a module you will still be able to contain these in much the same way you would a class.
If I could make a wish for the future of Javascript it would be to find some way that this is implicitly referring to the class in some way to have a smaller code style with less tokens and easier readability.