JS Learning Note 02-classes and objects, inheriting

Source: Internet
Author: User
Tags hasownproperty

Creating Classes and objects
//1)构造函数定义类,不用newfunction Dog(){ this.name = "Luby"; this.say = function(){  console.log("wangwang!"); }}let objDog = new Dog();  //创建对象的时候new//2)工厂方式定义类function Dog(){  let dog = new Object;  //变量,然后new Object;    dog.name = "Luby";    dog.say = function(){      console.log("wangwang");    }    return dog;}let dog = Dog();  //直接使用函数 //以上两种方式的缺点:每一个新的对象都需要创建一个say();//3)一般用原型+构造函数的方式定义类function Dog(){ this.name = "Luby";}Dog.prototype.say = function(){  console.log("wangwang!"); }let objDog = new Dog();  //
Constructor structure syntax
//构造函数并不声明局部变量,而是使用 this 关键字来保存数据//this 是指在构造函数前面使用 new 关键字创建的新对象function SoftwareDeveloper() {  this.useLanguage = ‘JavaScript‘;}let developer = new SoftwareDeveloper();
View the object's constructor (instanceof)
function SoftwareDeveloper() {  this.useLanguage = ‘JavaScript‘;}let developer = new SoftwareDeveloper();developer instanceof SoftwareDeveloper; // instanceof返回值为true;
Constructor property

Each time an object is created, a special property is implicitly assigned to it: constructor. Accessing the constructor property of an object returns a reference to the constructor that created the object!

function Cat(){ this.name = "fish";}let obj = new Cat();console.log(obj.constructor); //  ? Cat(){this.name = "fish";)

If an object is created using literal notation, its constructor is the built-in object () constructor!

let obj = { name: "fish"}console.log(obj.constructor);//  ? Object() { [native code] } // 和java的class一样(每个class都有一个无参的什么都不做得构造函数)
This

When the constructor is called using the new operator, the This variable is set to the newly created object. When a method is called on an object, this is set to the object itself. When a function is called in a browser environment, this is set to window, also known as a global object.

Summarize:

How the function is called determines the value of this in the function (who the current function belongs to or the object that currently occurs)
This in the constructor is the new object created with the new keyword before the constructor function

This application: Call (), apply (), bind () (callback function)

Call () is a method that calls directly to a function. We pass it a single value, set it to the value of this, and then pass through any parameters of the function, separated by commas.
The difference between apply () is that the number of arguments in the following is not known in advance for the number of arguments required by the function to use the Apply

const num = {  sum: function (n1,n2) {    return n1*n2;  }};const title = {  n1: 25,  n2: 18.0}console.log(num.sum.call(title,title.n1,title.n2));//450  相当于把.call前面的方法声明到obj这个对象里面console.log(num.sum.apply(title,[title.n1,title.n2]));

Use bind () to save this (the this in the callback function)

const dog = { age: 3, growOneYear: function(){ this.age +=1;}}function invokeTwice(cb) { cb(); cb();}invokeTwice(dog.growOneYear);//这里的this为windowconsole.log(dog.age); //3let change = dog.growOneYear.bind(dog);invokeTwice(change); //由bind指定了this为dogconsole.log(dog.age); //5
Window object

The URL of the page (window.location;)
Vertical scroll position of the page (window.scrolly)
Scroll to a new position (Window.Scroll (0, window.scrolly + 200), scroll down 200 pixels from the current position)
Open a new webpage (window.open ("https://www.sugarbeans.com/");)

Objects Object
var goods = new Object();Object.keys(goods);Object.values(goods);
Prototype inheritance prototype

Inheritance in JavaScript refers to an object that is based on another object
The key to inheritance in JavaScript is to build a prototype chain
When a function is called using the new operator as a constructor, the function creates and returns a new object. This object is secretly linked to the prototype of its constructor, and it is just another object. Using this secret link, you can have an object access the properties and methods of the prototype as if it were its own. If JavaScript does not find a specific attribute in an object, it will continue to look on the prototype chain . If necessary, it will look all the way to object () (top-level parent object)
Proto(note that each end has two underscores) is a property of all objects (that is, instances) created by the constructor and points directly to the prototype object of the constructor (warning: Do not use this property)
Simple Application

function Cat(){this.name = "coff";}let cat1 = new Cat();let cat2 = new Cat();Cat.prototype.say = function(){  console.log("woool");};Cat.prototype.color = "red" //添加属性Cat.prototype = { //指向了新的对象 color: "red"};console.log(cat1.__proto__); //  {say: ?, color: "red", constructor: ?}
Object.create ()

Prevents child objects from modifying the properties of the parent object, such as: Child.prototype.earBones = 5;
Object.create () takes an object as an argument and returns a new object whose proto property is set to the argument passed to it. Then, you only need to set the returned object as a prototype of the child object constructor.

const mammal = {   vertebrate: true,   earBones: 3};const rabbit = Object.create(mammal); //Object.create()console.log(rabbit);  // {}console.log(rabbit.__proto__ === mammal); //true
Inheritance between constructors
function Animal(name){  this.name = name;}Animal.prototype.walk = function(){  console.log(`${this.name} walks!`);} //定义了类Animalfunction Cat(name){  Animal.apply(this,[name]); //不使用new,使用父类的属性,如下:     //let obj = new Animal(name); // this.name = obj.name;}Cat.prototype = Object.create(Animal.prototype); //类Cat继承Animallet str = new Cat("miaomiao");console.log(str.walk());
Prototype-related functions

hasOwnProperty
hasOwnProperty () can help you find the source of a particular attribute. After you pass the string to the property name you want to find, the method returns a Boolean value that indicates whether the property belongs to the object itself (that is, the property is not inherited)

function Phone() {   this.operatingSystem = ‘Android‘;}Phone.prototype.screenSize = 6;const myPhone = new Phone();const own = myPhone.hasOwnProperty(‘operatingSystem‘); // trueconst inherited = myPhone.hasOwnProperty(‘screenSize‘); // false

isPrototypeOf () and object.getprototypeof ()
isPrototypeOf () can check if an object exists in the prototype chain of another object.
Object.getprototypeof () Determine what the prototype of an object is?

const dog = { name: "hero", age: 2}function Cat(){  this.say= function(){  console.log("miaomiao") };};Cat.prototype = dog;  //let str = new Cat();//str.say();方法已经被覆盖dog.isPrototypeOf(str); //true 注意调用顺序.const myPrototype = Object.getPrototypeOf(str); //获取原型console.log(myPrototype); //{name: "hero", age: 2}

JS Learning Note 02-classes and objects, inheriting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.