function Animal(name) { this.name = name; this.canWalk = true; } var dog = new Animal("dog"); // dog = { // name: "dog", // canWalk: true // }
function Clock(hours, minutes) { this.hours = hours; this.minutes = minutes; this.setTime = function(hours, minutes) { this.hours = hours; this.minutes = minutes; } this.displayTime = function () { alert(this.hours + ":" + this.minutes); } } var clock = new Clock(12, 30); var secondClock = new Clock(11, 45); clock.setTime(12, 45); clock.displayTime(); // 12:45 secondClock.displayTime(); // 11:45 console.log(clock instanceof Clock); // true
class Clock { constructor (hours, minutes) { this.hours = hours; this.minutes = minutes; } setTime (hours, minutes) { this.hours = hours; this.minutes = minutes; } displayTime () { alert(this.hours + ":" + this.minutes); } } var clock = new Clock(12, 30); var secondClock = new Clock(11, 45); clock.setTime(12, 45); clock.displayTime(); // 12:45 secondClock.displayTime(); // 11:45 console.log(clock instanceof Clock); // true
function Clock(hours, minutes) { var _hours = hours; var _minutes = minutes; this.setHours(hours) { _hours = hours; } this.getHours() { return _hours; } } var clock = new Clock(12, 30); alert(clock._hours); // undefined, "private" alert(clock.getHours()); // 12
let _hours; let _minutes; class Clock { constructor (hours, minutes) { _hours = hours; _minutes = minutes; } set hours(hours) { _hours = hours; } get hours () { return _hours; } } var clock = new Clock(12, 30); alert(clock.hours); // 12 clock.hours = 10; alert(clock.hours); // 10 alert(clock._hours); // undefined
function test(o) { alert(this.a, this.b); } var o1 = {a: 10, b: 20}; var o2 = {a: 100, b: 200}; test.call(o1); // 10, 20 test.call(o2); // 100, 200 var a = 1; var b = 2; test(); // 1, 2
var user = { title: 'user', greeting: function(){ return 'Hi, i am ' + this.title } } user.greeting(); // Hi, i am user var developer = Object.create(user); developer.title = 'developer'; developer.greeting()' // Hi, i am developer
var user = { firstName: "Petya" }; var admin = { firstName: "Vasya" }; function showName() { alert( this.firstName ); } user.a = showName; user.a(); // Petya showName.call(admin); // Vasya showName(); // undefined
a.func(); // this refers to the object, i.e., a.
func(); // this is bond to the global object.
func.apply(thisArg, argArray); // this is bond // to the first argument
var func = new Func(); // this refers to func // while in Func constructor)
var init = function () { this.clickCounter = 0; var that = this; var clickHandler = function () { that.clickCounter++; } var element = document.getElementById('button'); element.addEventListener('click', clickHandler); }