首页 > 其他分享 >Objects Revisited, Prototypes

Objects Revisited, Prototypes

时间:2023-02-02 13:35:33浏览次数:45  
标签:function console log object Prototypes Objects const Revisited speak

Object-Oriented Programming

Describe the following object oriented programming concepts: →

  • inheritance - basing a class off of another class so that it maintains the same behavior as its super class
  • polymorphism - having the same interface to instances of different types
  • encapsulation - information hiding, internals/implementation details not accessible publicly
  • abstraction  - (again) creating tools / interfaces that allow a programmer to address the actual problem they're solving rather than having to deal with necessary, but irrelevant (to the problem) details
 

Object-Oriented Programming in Java

In Java, what language features / constructs allow inheritance, polymorphism, encapsulation, and abstraction? →

  • inheritance - subclassing… using extend
  • polymorphism - instances of different classes that are subclasses of the same superclass
  • encapsulation - private methods and private members variables
  • abstraction - creating classes, interfaces, abstract classes, and methods

Object-Oriented Programming in JavaScript

Although JavaScript has objects, its approach to object-oriented programming is a bit unconventional.

  • it still supports encapsulationinheritancepolymorphism, and abstraction
  • … but it does so differently than Java (and other languages that support classical object-oriented techniques) →

 

  • inheritance - prototypes and/or functions
  • polymorphism - duck typing
  • encapsulation - closures
  • abstraction - higher order functions, prototypes, etc.

Globals

First off, in both Node and browser-based JavaScript implementations a global object exists:

  • global for node
  • window for browsers


Let's see what this looks like by: →

  • checking out global in the interactive shell
  • inadvertently creating a global variable within a function definition (dropping constlet, and var)
console.log(global.mistake);
function oopsGlobal() {
	mistake = "yup";
}
oopsGlobal();
console.log(mistake);
console.log(global.mistake);
 

Methods

Methods are object properties that are functions (a function within the context of an object).

const cat = {};
cat.speak = function() {
	console.log("meow"); 
};
cat.speak();

Notice that you can attach methods to any arbitrary object instance! (???)

This

Calling a function is called as a method - such as object.someFunction() — the special variable this in its body will reference the object that the method was called on. What will be printed out in the code below?. →

function speak() {
	if(this.nationality == "Japanese") {
		console.log("nyan");
	} else if (this.nationality == "American") {
		console.log("meow");
	} else {
		console.log("default cat noise");
	}
}
const japaneseCat = {nationality:"Japanese", speak:speak};
const americanCat = {nationality:"American", speak:speak};
japaneseCat.speak();
americanCat.speak();
nyan
meow
 

In methods, this refers to the object that the method was called on

 

Strict Mode / ESM Regular Function Invocation

When in strict mode (which is default when using ES Modules), this is undefined if a function is called on its own (that is, as a regular function invocation). What will the following code print out? →

const f = function() {
	console.log('this is', this);
}
f();
this is undefined

In "Sloppy" Mode, this in Regular Function Invocation

Things are much worse when you're not using ES Modules and you don't have strict mode on:

global.outside = 5;
const f = function() {
	console.log(this.outside);
}
f();
5

// this is the global object!
 

Standalone Functions and This

Aaaand… assuming ES Modules, what's the output of our speak function from the previous slide if we call it on its on (not within the context of an object)? →

function speak() {
	if(this.nationality == "Japanese") {
		console.log("nyan");
	} else if (this.nationality == "American") {
		console.log("meow");
	} else {
		console.log("default cat noise");
	}
}
speak();

This will actually cause an error! this is undefined, and looking up a property on undefined causes a runtime error

 

Another Way(s)

Besides method invocation and regular function invocationwhat are two other ways of executing a function? →

  • call - invoke function that call was called on with specified this and positional arguments
  • apply - invoke function that apply was called on with specified this and an Array containing positional arguments


When invoking a function with call or apply:

  • this will be bound to the value passed in as the first argument.
  • What's the output of the following code? →
function greet(person) { console.log(this.greeting, person); }
const obj = { greeting: 'hi' };
greet.call(obj, 'joe');
hi joe
 

Call and Apply Continued

Aaaand… of course, call and apply with our cat example (modified a bit). What is the output of this code? →

function speak(how, toWho) {
    const d = {Japanese: "nyans", American: "meows"};
    const noise = d[this.nationality] || "default cat noise";
    console.log(noise, how, 'at', toWho);
}
const cat = {nationality: "American"}

speak.apply(cat, ['loudly', 'you']);
speak.apply({}, ['softly', 'me']);
meows loudly at you
default cat noise softly at me
 

When executing a function with the methods call or applythis refers to the object passed in as the first argument to either method

Another Mystery?

What is the output of this code and why (assume ES Modules)? →

const counter = {numbers: [1, 2, 3, 4], animal:'owl'};

counter.count = function() {
    this.numbers.forEach(function(n) {
        console.log(n, this.animal + (n > 1 ? 's' : ''));
    });
};
counter.count();
error - `this` is `undefined`

The anonymous function is being invoked as a regular function for every element in the Arraycounter.numbersthis refers to undefined, which causes an error on property lookup

Same as Previous, but "Sloppy"

If the previous were run in sloppy mode (that is, not and ES Module and no use strict) →

1 'undefined'
2 'undefineds'
3 'undefineds'
4 'undefineds'

In sloppy mode, the this in the inner function is not invoked as a method, but instead as a regular function. Consequently (in sloppy mode), this is the global object.

Arrow Functions

In previous slides, we said that the this value in arrow functions is the this in the scope that the arrow function was created in (that is, it doesn't have it's own this, it just uses the one that's already there!

Let's see how this works: →

const counter = {numbers: [1, 2, 3, 4], animal:'owl'};

counter.count = function() {
    this.numbers.forEach((n) => {
        console.log(n, this.animal + (n > 1 ? 's' : ''));
    });
};
counter.count();
1 'owl'
2 'owls'
3 'owls'
4 'owls'

Better! this is whatever this refers to in the count method, and because count was invoked as a method, this is the object that count was called on.

Arrow Functions Continued

Of course, that means if we use the following code, what will this refer to? What is the output of the following code? →

function foo() {
    const bar = (x) => { console.log(this.qux); };
    bar();
}
foo();
undefined

this references this in the function, foo, which was invoked as a regular function. Consequently, this is the global object.

 

Summary

What is this?????

  1. regular function invocation
    • in ES Modules / strict mode, this is undefined
    • in sloppy mode, this is the global object
  2. method call
    • this is the object the method was called on
  3. invoked with call or apply
    • this is the first argument passed in to call or apply
  4. arrow function
    • this is this from the enclosing context

标签:function,console,log,object,Prototypes,Objects,const,Revisited,speak
From: https://www.cnblogs.com/M1stF0rest/p/17085599.html

相关文章

  • 08-从 objects 到 QuerySet
    调试特点如果B继承了A,那么在调试器中,只能看到B的直接属性或者方法,看不到它所继承的。先明白这一点Manager注意每一窗口下方的代码位置,方便快速定位代码。【1......
  • T-SQL:系统对象 SYSOBJECTS.XTYPE 各个值的含意
     SQLSERVER2008R2系统对象SYSOBJECTS.XTYPE 共有16个值,分别是:SELECTDISTINCTAO.TYPEASXTYPE,AO.TYPE_DESCFROMSYS.all_objectsAOXTYPETYPE_DESC......
  • Objects
    We'veexplored numbers, strings, booleans, undefined and functions abit,butwehaven'treallytalkedabout objects yet.Objects areessentially:......
  • API(Objects)
    Objects是一个对象工具类,提供了一些操作对象的方法equals(对象1,对象2),先做非空判断,在比较两个对象//1:objects.equals(对象名1,对象名2)用来先做非空判断,比较两个对象boolean......
  • pure js function merge URL objects All In One
    purejsfunctionmergeURLobjectsAllInOneQuestion//???OCR识别codehttps://twitter.com/wesbos/status/1613223775796924417/photo/1Solution"usest......
  • Lock objects should only be shared between processes through inheritance
    python的进程同步需要使用multiprocessing.Manager类型的对象来构造,普通的Lock不行defmain():iterable=[1,2,3,4,5]pool=multiprocessing.Pool()......
  • ArcObjects SDK开发 一些可直接调用的对话框
    在ArcMap中,一些对话框是很复杂的,例如设置点线面样式的对话框,选择空间参考的对话框等,但这些对话框有些在ArcObjectsSDK中是可以直接调用的。1、空间参考选择设置对话框弹......
  • ArcObjects SDK开发 025 AO中对象的序列化和反序列化
    在ArcObjectsSDK,序列化接口是IPersistStream,该接口的定义如下。其中GetClassID函数可以获取实际类型的唯一ID,Load函数是反序列化函数,Save函数为序列化函数。我们看下Loa......
  • ArcObjects控件间交互
    需要开发一个查询要素并实时显示查询信息的功能,用到了arcobjects可停靠窗口(dockableForm),交互当然是用arcobjtectsTool,如何在点击事件获取要素并获取相关信息后将信息传到d......
  • 第十一章《Java实战常用类》第7节:Objects类
    ​Objects类位于Java.util包,这个类与Object类的名称很相像,Java语言定义Objects类是为了让程序员能够以更加合理的方式操作对象。Objects类中定义的方法很多,这些方法可以分为......