Giter VIP home page Giter VIP logo

blog's People

Watchers

 avatar

blog's Issues

[javascript] function prototype的初淺理解

java中class 與instance

在java中,class是一個模版,class為模版,new出來的實例(instance)才能被直接使用

public class Person{
	private String name;
	private int age;
    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    public void sayName(){
        System.out.println(this.name);
    }
}

Person Mary = new Person("Mary", 25);
Mary.sayName(); // Mary

在上述範例中,Person是一個class,Mary是 以Person這個class 新建出來的實例,一般情況下我們都會對實例做操作。

javascript function prototype

在javascript中,function是一個object,所以有自己的屬性及方法。同時,function也可把自己當作模板使用

// 先創建一function, 即創建一object
function Person() {
}

// 設定該object的prototype屬性
Person.prototype.name = 'Nicholas';
Person.prototype.age = 29;
Person.prototype.sayName = function () {
    alert(this.name);
};

var person1 = new Person();
person1.sayName(); //”Nicholas” 
var person2 = new Person();
person2.sayName(); //”Nicholas” 

structure

Person1 和Person2都是以Person為模版new出來的,三者都有一Prototype屬性(指針),都是指向Person Prototype這個object (Person Prototype也是一object)。

而Person Prototype中的Construcotr會指向都是屬於哪一個object,即Person。

因所有以Person為模版建立出來的object 的Prototype都是指向Person Prototype,所以Person Prototype中有任何修改,所有Person為模版建立的舊object和未new出來的object都會被影響。

但在Person Prototype中有任何新增,舊的object並不會被影響到。原因為舊的object在被創建時就被分配指向一Prototype,在新增prototype的屬性時,其實為新建一個包含新屬性的prototype。新的object會指向新的prototype,舊object仍舊指向舊prototype,故舊object不會被影響到。

function Person() {}

Person.prototype = {
    constructor: Person,
    name: 'Mary',
    age: 29,
    sayName: function () {
        alert(this.name);
    }
};

var friend = new Person();
friend.sayName();  // Mary

// 修改prototype裡的屬性
Person.prototype.name = 'John';
friend.sayName(); // John

// 新增prototype裡的屬性
Person.prototype.height = 180;
Console.log(friend.height); // error

判別屬性是屬於instance還是prototpye

// 先創建一function, 即創建一object
function Person() {
}

// 設定該object的prototype屬性
Person.prototype.name = 'Nicholas';
Person.prototype.age = 29;
Person.prototype.sayName = function () {
    alert(this.name);
};

var person1 = new Person();
var person2 = new Person();

person1.name = “Greg”; 
alert(person1.name); //”Greg” - from instance 
alert(person1.hasOwnProperty(“name”)); //true

alert(person2.name); //”Nicholas” - from prototype
alert(person2.hasOwnProperty(“name”)); //false

delete person1.name; 
alert(person1.name); //”Nicholas” - from the prototype 
alert(person1.hasOwnProperty(“name”)); //false

9. Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

public bool IsPalindrome(int x) {
            String s = x.ToString();
            int ind1 = 0, ind2 = s.Length - 1;
            while(ind1 < ind2)
            {
                if (s[ind1] != s[ind2]) return false;
                ind1++;
                ind2--;
            }
            return true;
    }

後來發現題目有要求不能轉string

        public bool IsPalindrome(int x)
        {
            int ori = x;
            int tail;
            int reverse = 0;
            if (x < 0) return false;
            while(x > 0)
            {
                tail = x % 10;
                x /= 10;

                reverse *= 10;
                reverse += tail;
            }
            if (ori == reverse) return true;
            return false;
        }

官方答案: 由於是對稱, 可只比較一半的數
如何知道已經到達一半? reverseNum>= oriNum 時

if (ori == reverse) return true;
return false;

//可直接寫成
return ori == reverse;

7. Reverse Integer

Question

Given a 32-bit signed integer, reverse digits of an integer.

note

以二進制的角度切入
bit shift
bit operator
hexadecimal numbers prefix: 0x
二進制: 0b

但十進制的對稱不等於二進制的對稱
後改以十進制角度切入

Input: 1534236469
Output: 1056389759
Expected: 0
1534236469 => 9646324351 > (2^31-1), 應return 0

問題變成如何檢驗overflow?

注意的點有兩個
產生數前, 先做檢驗會否產生超出Int32.MaxValue的數?
產生non-overflow數a、b後, 檢驗相加和會否超出Int32.MaxValue
https://stackoverflow.com/questions/199333/how-do-i-detect-unsigned-integer-multiply-overflow

        public int Reverse(int x)
        {
            int firstDigital, firstDigitalInd = 0;
            int result = 0, temp = 0;
            for (int ind = 12; ind >= 0; ind--)
            {
                firstDigital = (int)(x / Math.Pow(10, ind));
                firstDigital = firstDigital % 10;

                // skip first 0
                if (firstDigital == 0 && firstDigitalInd == 0)
                    continue;
                if (firstDigitalInd == 0)
                    firstDigitalInd = ind;

                if ((firstDigital > 2 || firstDigital < -2) && (firstDigitalInd - ind) >= 9) return 0;
                temp = firstDigital * (int)Math.Pow(10, (firstDigitalInd - ind));

                if ((temp > 0) && (result > Int32.MaxValue - temp)) return 0;
                if ((temp < 0) && (result < Int32.MinValue - temp)) return 0;
                result += temp;
            }
            return result;
        }

Review

官方答案為last digit開始往回操作, 我的答案是由第一位數開始操作
定義好pop & push 會簡潔很多

//pop operation:
pop = x % 10; // get last digital
x /= 10; // prepare next pop

//push operation:
temp = rev * 10 + pop;
rev = temp;

3. Longest Substring Without Repeating Characters

題目

Given a string, find the length of the longest substring without repeating characters.

public static int LengthOfLongestSubstring(string s)
{
    // last status:
    int tailInd = 0, headInd = 0, maxLen = 0;
    int tempInd, ind1;
    Dictionary<char, int> dict = new Dictionary<char, int>();
    int curLen = 0;
    for (tailInd = 0; tailInd < s.Length; tailInd++)
    {
        char aChar = s[tailInd];
        if (dict.ContainsKey(aChar))
        {
            if (!dict.TryGetValue(aChar, out tempInd))
            {
                throw new Exception("TryGetValue Error");
            }
            for(ind1 = headInd; ind1 <= tempInd; ind1++)
            {
                dict.Remove(s[ind1]);
            }
            headInd = tempInd  + 1;
        }
        dict.Add(aChar, tailInd);
        curLen = dict.Count;
        if (curLen > maxLen)
        {
            maxLen = curLen;
        }
    }
    return maxLen;
}

心得

sliding windows 理論

A sliding window is an abstract concept commonly used in array/string problems. A window is a range of elements in the array/string which usually defined by the start and end indices, i.e. [i, j)[i,j) (left-closed, right-open). A sliding window is a window "slides" its two boundaries to the certain direction. For example, if we slide [i, j)[i,j) to the right by 11 element, then it becomes [i+1, j+1)[i+1,j+1) (left-closed, right-open).

只儲存一個value => hashSet
儲存key, value => hashMap

用Math.max() 取代比較大小值

java 中的hashMap 能 put 重覆key值, 會取代舊value
C# 中則不能, 會發exception

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.